【问题标题】:how to set width of a column in excel to max length of a cell value using openpyxl?如何使用openpyxl将excel中列的宽度设置为单元格值的最大长度?
【发布时间】:2020-01-02 16:07:17
【问题描述】:
##########################
#working with xlsx files #
##########################

import openpyxl
from openpyxl.styles import Font, PatternFill, Border, Side, Alignment
import os
import datetime

my_cellstatus_headders = ['Server Name','Cell Name','Role','Current Status','Expected Status','Health']
log_path = 'C:\\Users\\686559\\Desktop\\TESTPERL\\TESTPYTHON\\Create_excel\\bin\\Infra_Health_Status.xlsx'

thin_border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))
alignment = Alignment(horizontal='center',vertical='bottom',text_rotation=0,wrap_text=False,shrink_to_fit=False,indent=0)

try:
    mywb = openpyxl.Workbook()
except:
    print ("Couldn't create the file ", log_path)
sheet = mywb.active
sheet.title = "Cell_Status"

for i in range (1,7):
    sheet.cell(row=1,column=i).value = my_cellstatus_headders[i-1]
    sheet.cell(row=1,column=i).font = Font(bold=True)
    sheet.cell(row=1,column=i).fill = PatternFill(fgColor="D8D8D8", fill_type = "solid")
    sheet.cell(row=1,column=i).border = thin_border
    sheet.cell(row=1,column=i).alignment = alignment


columns = sheet.columns
#help (columns)
for col in columns:
    max_length = 0
    #print (col)
    for cell in col:
       try:
          if len(str(cell.value)) > max_length:
                max_length = int(len(cell.value))
       except:
            pass
       adjusted_width = max_length
       sheet.column_dimensions['col'].width = adjusted_width
try:
    mywb.save(log_path)
except:
    print ("Could not save the file ",log_path)

但是正在创建的 excel 工作表没有将列的宽度设置为单元格中的最大字符数。任何帮助或想法表示赞赏。

当前输出:

预期输出:

【问题讨论】:

  • 这能回答你的问题吗? openpyxl - adjust column width size
  • 嗨@APhillips,我对脚本很陌生,你能帮我修改上面的代码吗?或者您能否在您提供的链接中解释每行正确标记答案的重要性。再次感谢您的帮助。
  • 能否请您从链接中解释正确答案:stackoverflow.com/questions/13197574/…
  • 您没有在任何地方设置列宽。
  • 嗨@CharlieClark,对,在我获得变量“adjusted_width”中的最大宽度后,如何将其设置为该特定列?

标签: python-3.x reporting openpyxl


【解决方案1】:
##########################
#working with xlsx files #
##########################

import openpyxl
from openpyxl.styles import Font, PatternFill, Border, Side, Alignment
import os
import datetime
import re

my_cellstatus_headders = ['Server Name','Cell Name','Role','Current Status','Expected Status','Health']
log_path = 'C:\\Users\\686559\\Desktop\\TESTPERL\\TESTPYTHON\\Create_excel\\bin\\Infra_Health_Status.xlsx'

thin_border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))
alignment = Alignment(horizontal='center',vertical='bottom',text_rotation=0,wrap_text=False,shrink_to_fit=False,indent=0)

try:
    mywb = openpyxl.Workbook()
except:
    print ("Couldn't create the file ", log_path)
sheet = mywb.active
sheet.title = "Cell_Status"

for i in range (1,7):
    sheet.cell(row=1,column=i).value = my_cellstatus_headders[i-1]
    sheet.cell(row=1,column=i).font = Font(bold=True)
    sheet.cell(row=1,column=i).fill = PatternFill(fgColor="D8D8D8", fill_type = "solid")
    sheet.cell(row=1,column=i).border = thin_border
    sheet.cell(row=1,column=i).alignment = alignment


columns = sheet.columns
#help (columns)
for col in columns:
    max_length = 0
    #print (col)
    for cell in col:
       try:
          if len(str(cell.value)) > max_length:
                max_length = int(len(cell.value))
       except:
            pass
       adjusted_width = max_length
       #print (col[0]) #<Cell 'Cell_Status'.A1>
       #https://stackoverflow.com/questions/13197574/openpyxl-adjust-column-width-size
       col_name = re.findall('\w\d', str(col[0])) #pull the last letter+digit
       col_name = col_name[0]
       col_name = re.findall('\w', str(col_name))[0]
       #print (col_name)
    sheet.column_dimensions[col_name].width = adjusted_width+2
try:
    mywb.save(log_path)
except:
    print ("Could not save the file ",log_path)

这对我有用,有什么办法让它变得更好吗?请建议。谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-09
    • 2023-03-23
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 2012-12-03
    相关资源
    最近更新 更多