gpt4 book ai didi

excel - 单个 Excel 工作表中的多个 NamedStyle - Python openpyxl

转载 作者:行者123 更新时间:2023-12-04 19:49:48 29 4
gpt4 key购买 nike

我正在尝试为 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")

最佳答案

看起来非常像您正在加载的书中已经存在的样式,因为异常与您的功能无关。您可能希望使用 book.named_styles 添加检查。

关于excel - 单个 Excel 工作表中的多个 NamedStyle - Python openpyxl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50560011/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com