openpyxl ValueError 格式化新数据行

openpyxl ValueError formatting new rows of data

下面的代码在我第一次 运行 时效果很好(当它创建一个新的传播时 sheet)。 当我再次尝试 运行 它(更新现有 sheet)以添加更多数据(其他行)时,我收到以下错误

回溯(最后一次调用): 文件“C:/PythonPrograms/Workout Program/test_excel_format.py”,第 35 行,位于 cell.style = wdata

文件“C:\Users\Mark\AppData\Local\Programs\Python\Python37\lib\site-packages\openpyxl\styles\named_styles.py”,第 193 行,追加 raise ValueError("""样式 {0} 已经存在""".format(style.name)) ValueError:样式 wdata 已经存在

   from openpyxl import Workbook
   from openpyxl.styles import PatternFill
   from openpyxl import load_workbook
   from openpyxl.styles import Font, Color, Alignment, Border, Side, colors
   from openpyxl.styles import NamedStyle
   from datetime import date
   from os import path

   filename = "format_wb_test.xlsx"

   if path.exists(filename):
      workbook = load_workbook(filename)
   else:   
      workbook = Workbook()    

   sheet = workbook.active

   tdate = date.today()

   data = [tdate, "Data 1", "Data 2", "Data 3"]

   wdata = NamedStyle(name="wdata")
   wdata.font = Font(bold=True)
   wdata.alignment = Alignment(horizontal="center", vertical="center")

   for x in range(1, 3):
       sheet.append(data) # appends the data to the first empty row.
       print("current row: ", sheet._current_row)
       ucell = "A" + str(sheet._current_row)
    
       wdata_row = sheet[sheet._current_row]
       for cell in wdata_row:
              cell.style = wdata

       sheet[ucell] = tdate

   workbook.save(filename=filename) 

我希望能够在我 运行 这段代码时添加新的格式化数据行。

我看不出有任何方法可以使用 NamedStyle 来更新添加到现有的行的格式 workbook/sheet。如果您定义 NamedStyle,则会收到“已存在”错误。如果不这样做,则会收到“未定义 NamedStyle”的错误。该文档几乎逐字逐句地陈述了查理克拉克在他上面的评论中所说的内容,“样式在首次使用时自动注册,然后可以通过名称引用。”它没有详细说明或显示如何使用现有 NamedStyle 的示例。鉴于此,我放弃了尝试使用 NamedStyle 并按如下方式更新代码以使其工作。如果有办法用 NamedStyle 做到这一点,我很乐意看到它。

这是更新后的代码。

from openpyxl import Workbook
from openpyxl.styles import PatternFill
from openpyxl import load_workbook
from openpyxl.styles import Font, Color, Alignment, Border, Side, colors
from openpyxl.styles import NamedStyle
from datetime import date
from os import path

filename = "format_wb_test.xlsx"

if path.exists(filename):
   workbook = load_workbook(filename)
else:   
   workbook = Workbook()    

sheet = workbook.active

tdate = date.today()

data = [tdate, "Data 1", "Data 2", "Data 3"]

#   wdata = NamedStyle(name="wdata")
#   wdata.font = Font(bold=True)
#   wdata.alignment = Alignment(horizontal="center", vertical="center")

for x in range(1, 3):
    sheet.append(data) # appends the data to the first empty row.
    print("current row: ", sheet._current_row)
    ucell = "A" + str(sheet._current_row)   
    wdata_row = sheet[sheet._current_row]
    for cell in wdata_row:
        #cell.style = wdata
        sheet[str(cell.coordinate)].font = Font(bold=True)
        sheet[str(cell.coordinate)].alignment = Alignment              \
                (horizontal="center", vertical="center")
    sheet[ucell] = tdate

workbook.save(filename=filename)