在 Openpyxl Python 中将列格式化为百分比



我只想使用 Openpyxl for Python 将某些列制作成百分比。我不知道如何将单元格的格式更改为另一种类型?

我查阅了此页面:

http://openpyxl.readthedocs.io/en/default/styles.html

但是如果我尝试这样做:

ws['A:A'].style = percent

我得到值错误:样式百分比已经存在。我确定我犯了一些愚蠢的错误,但我无法弄清楚它是什么。我见过其他关于人们想要将格式更改为货币的线程,它们使用不同的数字格式,但没有关于百分比的内容。

您只能设置单个单元格的格式,而不能设置单元格区域、列或行的格式。

@gianluca-tarasconi 根据您对样式文档 https://openpyxl.readthedocs.io/en/stable/styles.html 的评论,它仍然一次适用于一个单元格。有没有办法,可以设置整行或整列或单元格范围的样式。我尝试了不同的东西只是为了得到AttributeError: 'tuple' object has no attribute 'style'

向细胞组添加百分比的失败实验:

In [23]: from openpyxl.styles.numbers import FORMAT_PERCENTAGE
In [27]: from openpyxl.styles import NamedStyle
In [31]: highlight = NamedStyle(number_format=FORMAT_PERCENTAGE, name="percent_style")
In [32]: wb.add_named_style(highlight)  # wb is workbook
In [33]: ws1["B"].style = highlight  # ws1 is worksheet
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [33], in <cell line: 1>()
----> 1 ws1["B"].style = highlight
AttributeError: 'tuple' object has no attribute 'style'

In [34]: ws1["B1:B5"].style = highlight
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [34], in <cell line: 1>()
----> 1 ws1["B1:B5"].style = highlight
AttributeError: 'tuple' object has no attribute 'style'

In [37]: ws1["B:B"].style = highlight
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [37], in <cell line: 1>()
----> 1 ws1["B:B"].style = highlight
AttributeError: 'tuple' object has no attribute 'style'

成功的实验是针对单个元素的:

In [35]: for val in ws1["B"]:
...:     val.style = highlight # Saved xlsx file contains percent values.

In [43]: for val in ws1["C"]:
...:     val.number_format = FORMAT_PERCENTAGE # Saved xlsx file contains percent values here in column C as well.

目前,我只能想到@charlie克拉克You can only format individual cells not cell ranges or columns or rows.的答案是正确的。

想知道是否有任何方法可以格式化(在本例中使用百分比(列/行/组单元格。

最新更新