pandas df.to_excel 设置列宽遇到 AttributeError: 'Worksheet' object has no attribute 'column_dimensions'

df.to_excel底层默认优先用的是xlsxwriter,sheet对象的类型是 xlsxwriter.worksheet.Worksheet,它没有column_dimensions属性。
可以通过在创建ExcelWriter的时候指定engine="openpyxl"让底层使用openpyxl,sheet对象的类型会变成openpyxl.worksheet.worksheet.Worksheet,它是有column_dimensions属性的。
需要安装过 openpyxl 库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
with pd.ExcelWriter(f"xxx.xlsx",
engine="openpyxl",
date_format="YYYY-MM-DD",
datetime_format="YYYY-MM-DD HH:MM:SS"
) as writer:
df.to_excel(writer)
sheet = writer.sheets["Sheet1"]
# 设置列宽
sheet.column_dimensions['A'].width = 12.5
# 设置行高
sheet.row_dimensions[1].height = 72
# 设置表头(第一行)自动换行
r = sheet[1]
for c in r:
c.alignment = openpyxl.styles.Alignment(wrapText=True)
# 设置表体数字格式显示4位小数
for i, r in enumerate(sheet):
for j, c in enumerate(r):
if i != 0 and j != 0:
c.number_format = "0.0000"