【发布时间】: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