使用openpyxl格式化xlsx(数字格式,适合文本和缩小文本)

Use openpyxl to format the xlsx (number format, fit the text and shrink the texts)

我想使用 openpyxl(不要使用其他库)通过以下代码编辑 xlsx:

from openpyxl import Workbook
book = Workbook()
sheet = book.active
rows = [['name', 'This is number1', 'This is number2', 'longstr'],
['a', 312318.231, -2312.2, 'aaaaaaaaaaaa\naaaaaaaaaaaa\naaaaaaaaaaaa'],
['a', 312318.231, -2312.2, 'aaaaaaaaaaaa\naaaaaaaaaaaa\naaaaaaaaaaaa']
]
for row in rows:
    sheet.append(row)
book.save('text.xlsx')

结果如下:

我要的是

  1. 将第 2、3 列中的数字格式化为逗号样式(千位分隔符)并递减为无小数。我在代码中使用了 "{:,.0f}".format(),但是 xlsx 中的输出变成了一个字符串。

  2. 让单元格适合第 1、2、3 列的文本

  3. 缩小文本以适合第 4 列(不是标题)的单元格。在 excel 中,操作是 Format Cells -> Alignment -> Shrink to fit

以上是简化的示例,在实际情况下我们有数千行和已知的列数(比如 4 列)。

我是新手openpyxl,你能帮我实现我的目标吗?

列格式

要控制 Excel 中的数字显示格式,您可以这样设置单元格属性:

cell.number_format = "0.0000" # 4 decimal places

列宽

设置宽度类似,但作为列属性:

sheet.column_dimensions['A'].width = 12.5

很遗憾,您需要手动计算宽度,但没有好的方法。我发现 an example on the web 列出了 Calibri 11 字体的所有宽度指标(Excel 中的默认值)。你可以看看那边的列宽是怎么计算的

适合收缩...

from openpyxl.styles import Alignment

ws['A1'].alignment = Alignment(shrinkToFit=True, horizontal='center')

...应该这样做。