十、Openpyxl自定義單元格樣式

自定義單元格樣式

語(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')

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容