首页 > 解决方案 > 如何使用openpyxl将excel中列的宽度设置为单元格值的最大长度?

问题描述

##########################
#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 工作表没有将列的宽度设置为单元格中的最大字符。任何帮助或想法表示赞赏。

电流输出: 在此处输入图像描述

预期输出: 在此处输入图像描述

标签: python-3.xreportingopenpyxl

解决方案


##########################
#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)

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


推荐阅读