我正在尝试为excel工作表中的多个单元格设置样式。工作表中有多个表格。表头有粗体字和普通边框,而表数据只有顺序。
我已经定义了2个NamedStyle并附加到工作簿。但是当我对单元格的样式出现误差时。
book.add_named_style(tableHeaderStyle)
File "C:\Users\bsingh\AppData\Local\Programs\Python\Python36-32\lib\site-packages\openpyxl\workbook\workbook.py", line 303, in add_named_style
self._named_styles.append(style)
File "C:\Users\bsingh\AppData\Local\Programs\Python\Python36-32\lib\site-packages\openpyxl\styles\named_styles.py", line 194, in append
raise ValueError("""Style {0} exists already""".format(style.name))
ValueError: Style TableHeaderStyle exists already
代码:
from openpyxl.styles import Border, Side, Color, PatternFill, Font, Alignment, NamedStyle
my_border = Border(left=Side(border_style='thin', color='000000'),
right=Side(border_style='thin', color='000000'),
top=Side(border_style='thin', color='000000'),
bottom=Side(border_style='thin', color='000000'))
normalBorderStyle = NamedStyle(name="NormalBorderStyle",
alignment=Alignment(horizontal='center', vertical='center', wrap_text=True), border=my_border)
tableHeaderStyle = NamedStyle(name="TableHeaderStyle", alignment=Alignment(horizontal='center', vertical='center'), border=my_border, \
font=Font(bold=True), \
fill=PatternFill(patternType='solid', fill_type='solid', fgColor=Color('C4D79B')))
#This function is called for a table in worksheet "ws" with the cell range as the start and end column of table "B3:G7".
def set_border(ws, cell_range):
flag = 0
for row in ws.iter_rows(cell_range):
for cell in row:
cell.style = "NormalBorderStyle"
if flag ==0 :
cell.border = "TableHeaderStyle"
flag = 1
book = load_workbook(xlsfile)
book.add_named_style(tableHeaderStyle)
book.add_named_style(normalBorderStyle)
ws_active = book.get_sheet_by_name("Summary")
set_border(ws_active, "B3:G7")
答案 0 :(得分:0)
它看起来非常类似于您正在加载的书中已存在的样式,因为该异常与您的功能无关。您可能希望使用book.named_styles
添加支票。