import os, openpyxl
from openpyxl.styles import Font, Style
os.chdir("C:\\")
wb = openpyxl.Workbook()
sheet = wb['Sheet']
italic24Font = Font(size = 24, italic = True)
styleObj = Style(font = italic24Font)
sheet['A'].style/styleObj
sheet['A1'] = 'Hello world!'
wb.save('styled.xlsx')
自学《Python编程快速上手》P232的内容,运行下面代码时,程序报错
问题分析: openpyxl的后续版本有所修改,此外,《Python编程快速上手》的原著作者后续也已对该内容做了修改。
见链接:https://automatetheboringstuff.com/chapter12/
正确代码:
1 import os, openpyxl
2 from openpyxl.styles import Font
3 os.chdir("C:\\")
4 wb = openpyxl.Workbook()
5 sheet = wb['Sheet']
6 italic24Font = Font(size = 24, italic = True)
7 sheet['A1'].font = italic24Font
8 sheet['A1'] = 'Hello world!'
9 wb.save('styled.xlsx')
补充: 如果要对A列进行格式设置,则代码书写为:sheet.column_dimensions['A'].font = italic24Font。参见链接:点击打开链接 |