原因:當我們定義並調用了一次Style之後,以後的調用需要直接使用該Style的字符串形式。否則會報錯Style highlight exists already。一般程序運行第二次時會出現報錯,如果沒有用字符串形式引用的話。
wb.add_named_style(highlight)#第一步
ws[‘A1‘].style = highlight#第二步
Once registered assign the style using just the name:
ws[‘E2‘].style = ‘highlight‘#以後就可以直接調用字符串形式了
注意:
不同的對象之間是可以共享同一個Styles的,並且一旦爲對象指定了Styles之後就不可以再次更改。這是爲了在更改很多的單元格的Styles而不僅只是更改一個單元格時能夠避免不必要的副作用。
實例:
//定義
highlight = NamedStyle(name="highlight")
//定義字體樣式
highlight.font = Font(name='Consolas', size=11, bold=False, italic=False, vertAlign=None, underline='none',strike=False, color='FF000000')
//定義填充樣式
highlight.fill = PatternFill("solid", fgColor="DDDDDD") # 背景填充
//定義邊框樣式
bd = Side(style='thin', color="000000")
highlight.border = Border(left=bd, top=bd, right=bd, bottom=bd)
//調用
ws['A1'] = ‘highlight’
或者
for row in ws.rows:
for cell in row:
cell.style = 'highlight'
顏色代碼對應表:
http://www.360doc.com/content/13/1120/12/14695328_330723062.shtml