当前位置: 代码迷 >> python >> python中的openpyxl.styles模块问题,无法设置字体属性
  详细解决方案

python中的openpyxl.styles模块问题,无法设置字体属性

热度:31   发布时间:2023-07-16 10:07:49.0

使用openpyxl.styles.Font()函数时遇到问题,我也在文档中看到它也以这种方式讲授,因此不确定可能发生了什么变化。

>>> import openpyxl
>>> from openpyxl.styles import Font

>>> wb = openpyxl.Workbook()
>>> sheet = wb.get_sheet_by_name('Sheet')

>>> font_style = Font(sz=30, i=True)

>>> sheet['A1'].font = font_style

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    sheet['A1'].font = font_style
AttributeError: can't set attribute

我也这样尝试过:

sheet['A1'].font = Font(size=30, italic=True)
sheet['A1'].font = Font(sz=30, i=True)

当我尝试将单元格设置为字体样式时收到此错误消息,似乎没有任何作用。

任何建议表示赞赏,谢谢。

我认为您使用的是旧版本的openpyxl因为我无法重现openpyxl版本的问题。

尽管如此,还是有些奇怪:您正在尝试从新编制的工作簿中获取“工作表”工作表。 因此,此工作表不存在。

你应该试试:

import openpyxl

from openpyxl.styles import Font

wb = openpyxl.Workbook()
sheet = wb.create_sheet('Sheet')
font_style = Font(sz=30, i=True)
sheet['A1'].font = font_style

这将创建一个名为“ Sheet”的新工作表,并定义第一个单元格的字体。