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

Issue with openpyxl.styles module in python, unable to set font attribute

在使用 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 因为我无法使用 v2.5.8 版本重现您的问题。

然而,有一些奇怪的事情:您正在尝试从新创建的工作簿中获取 "Sheet" 工作sheet。所以这个 sheet 不存在。

你应该试试:

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" 的新作品sheet 并定义第一个单元格的字体。