|
发表于 2020-4-26 04:25:29
|
显示全部楼层
本帖最后由 nonamenochat 于 2020-4-26 04:29 编辑
思路五:命名样式 报错问题
我来补充一下,如果单纯按照小甲鱼老师的这个代码敲会报错,我就是在错误中过来的。
我把我的错误分3点给大家说一下,节省像我这样的新手的时间。
#第一 要import openpyxl模块,并且打开你要工作的工作簿+工作表
import openpyxl
wb = openpyxl.load_workbook("python_font_test.xlsx")
ws = wb['Sheet'] # 获取指定工作表
#第二 要在第二代码里除了导入NamedStyle,还要导入任何第想要修改的格式 Font,Alignment,Border,Side
from openpyxl.styles import NamedStyle,Font,Alignment,Border,Side
#第三点 我想说的是一旦你的样式创立,下次引用是只要引用名字即可
ws['B5'].style = 'highlight' #(注意这里有加英文格式引号)
下面是我的代码给大家参考,注意文件地址要改为你自己的
import openpyxl
from openpyxl.styles import NamedStyle,Font,Alignment,Border,Side
wb = openpyxl.load_workbook("python_font_test.xlsx")
ws = wb['Sheet'] # 获取指定工作表
highlight = NamedStyle(name="highlight")
highlight.font = Font(bold=True, size=20)
bd = Side(style='thick', color="000000")
highlight.border = Border(left=bd, top=bd, right=bd, bottom=bd)
highlight.alignment = Alignment(horizontal='center', vertical='center')
wb.add_named_style(highlight)
ws['A1'].style = highlight
ws['B5'].value = "LOVE"
ws['B5'].style = 'highlight'
wb.save("python_font_test.xlsx") |
|