自定義單元格樣式
語(yǔ)法
NamedStyle( name="Normal",
font=Font(),
fill=PatternFill(),
border=Border(),
alignment=Alignment(),
number_format=None,
protection=Protection(),
builtinId=None,
hidden=False,
xfId=None )
參數(shù)就沒(méi)有什么好說(shuō)的了,name就是這個(gè)自定義樣式的名字,然后對(duì)設(shè)置了該樣式的單元格設(shè)置font, fill , border, alignment, number_format, protection等。后面三個(gè)參數(shù)省略。(id就是在單元格樣式列表中的索引,用name就好了)
實(shí)例
import openpyxl
from openpyxl.styles import NamedStyle, Font, Border, Side, PatternFill, Alignment
wb = openpyxl.Workbook()
ws = wb.active
ws.append(['name','number','unit','price'])
ws.append(['A',2,5,0])
ws.append(['A',2,5,0])
ws.append(['A',2,5,0])
ws.append(['A',2,5,0])
ws.append(['A',2,5,0])
mySide = Side(style='thin',color='1E1E1E')
# 標(biāo)題樣式
TitleStyle = NamedStyle(name='TitleStyle',
font=Font(name='宋體',size=14,bold=True),
fill=PatternFill(fill_type='solid',start_color='1BA135'),
border=Border(left=mySide,top=mySide,right=mySide,bottom=mySide),
alignment=Alignment(horizontal='center',vertical='center'))
# 正文樣式
BodyStyle = NamedStyle( name='BodyStyle',
font=Font(name='宋體',size=12),
border=Border(left=mySide,top=mySide,right=mySide,bottom=mySide),
alignment=Alignment(horizontal='center',vertical='center'))
# 把自定義的樣式添加到工作簿
wb.add_named_style(TitleStyle)
wb.add_named_style(BodyStyle)
# 應(yīng)用到工作表中
for c in range(1,5):
ws.cell(1,c).style = TitleStyle
for r in range(2,7):
for c in range(1,5):
ws.cell(r,c).style = BodyStyle
wb.save(r'/Users/junliangchen/Desktop/test.xlsx')