如何使用openpyxl将Excel中的列宽设置为单元格值的最大长度?

问题描述 投票:0回答:1
##########################
#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工作表未将列的宽度设置为单元格中的最大字符。任何帮助或想法表示赞赏。

当前输出:enter image description here

预期输出:enter image description here

python-3.x reporting openpyxl
1个回答
0
投票
##########################
#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)

这对我有用,有什么方法可以使它更好?请提出建议。谢谢

© www.soinside.com 2019 - 2024. All rights reserved.