自定义单元格样式
语法
NamedStyle( name="Normal",
font=Font(),
fill=PatternFill(),
border=Border(),
alignment=Alignment(),
number_format=None,
protection=Protection(),
builtinId=None,
hidden=False,
xfId=None )
参数就没有什么好说的了,name就是这个自定义样式的名字,然后对设置了该样式的单元格设置font, fill , border, alignment, number_format, protection等。后面三个参数省略。(id就是在单元格样式列表中的索引,用name就好了)
实例
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')
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)
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')