Excel中Python设置样式和字体大小
这是我的代码,请注意:我目前正在学习Python:Excel中Python设置样式和字体大小,python,excel,Python,Excel,这是我的代码,请注意:我目前正在学习Python: import openpyxl from openpyxl.styles import Font wb = openpyxl.Workbook() sheet = wb.get_sheet_by_name('Sheet') italic24Font = Font(size=24, italic=True) sheet['A1'].font = italic24Font sheet['A1'] = 'Hello world!' wb.save('
import openpyxl
from openpyxl.styles import Font
wb = openpyxl.Workbook()
sheet = wb.get_sheet_by_name('Sheet')
italic24Font = Font(size=24, italic=True)
sheet['A1'].font = italic24Font
sheet['A1'] = 'Hello world!'
wb.save('styled.xlsx')
以下是我的错误消息:
Traceback (most recent call last):
File "<pyshell#94>", line 1, in <module>
sheet['A1'].font = italic24Font
AttributeError: can't set attribute
TypeError: cannot set size attribute
我得到的结果是:
['UNDERLINE_DOUBLE', 'UNDERLINE_DOUBLE_ACCOUNTING', 'UNDERLINE_SINGLE', 'UNDERLINE_SINGLE_ACCOUNTING', '__add__', '__base__', '__class__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__fields__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__print__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__sub__', '__subclasshook__', '__weakref__', '_key', '_make_key', 'b', 'bold', 'charset', 'color', 'condense', 'copy', 'extend', 'family', 'i', 'italic', 'name', 'outline', 'scheme', 'shadow', 'size', 'spec', 'strike', 'strikethrough', 'sz', 'u', 'underline', 'vertAlign']
我试着运行这个:
sheet['A1'].font.size=24
但我得到了这个错误信息:
Traceback (most recent call last):
File "<pyshell#94>", line 1, in <module>
sheet['A1'].font = italic24Font
AttributeError: can't set attribute
TypeError: cannot set size attribute
有趣
编辑#3:
print(sheet['A1'].style.font.size)
11.0
但当我尝试时:
sheet['A1'].style.font.size=11
我收到以下错误消息:
Traceback (most recent call last):
File "<pyshell#94>", line 1, in <module>
sheet['A1'].font = italic24Font
AttributeError: can't set attribute
TypeError: cannot set size attribute
无法设置大小属性
我按原样运行了你的代码。它执行时没有AttributeError或任何其他错误。首先,检查您是否具有修改
工作表
设置的正确权限。其次,检查您的openpyxl
包是否已更新到当前版本(可能旧版本中的语法有所不同)
通常,当您试图为属性/属性设置值时,会引发AttributeError,该属性/属性由于没有setter而无法设置