XlsxWriter 中意外的单元格格式化行为

Unexpected cell formatting behaviour in XlsxWriter

使用 xlsxwriter 创建电子表格。设置格式:

fmt_title = self.workbook.add_format({
    'font_name': 'FreeSans',
    'font_size': 14,
    'font_color': '#0066B3',
    'bold': True,
})

我将格式应用于合并的行,然后更改了字体大小(目的是用较小的字体大小写入另一行)

self.worksheet.merge_range('A1:G1', 'Font Size SHOULD be 14',fmt_title)
fmt_title.set_font_size(12)
self.worksheet.merge_range('A2:G2', 'Font Size SHOULD be 12',fmt_title)

我 运行 遇到的问题是在更改字体大小后,所有应用格式的行都更改为 12 的字体大小。为什么格式在我写完行后发生变化?

要认识到的关键是实际 excel 文件的写入仅在执行 workbook.close() 语句后才开始。

所以基本上你的 fmt_title 格式化对象在执行 worksheet.merge_range('A1:G1', 'Font Size SHOULD be 14',fmt_title) 期间还不是真正的 'used'。仅存储对格式化对象的引用供以后使用。

xlsxwriter documentation 确认您所看到的是正常行为(尽管不可否认它最初可能是 counter-intuitive):

Modifying Formats

Each unique cell format in an XlsxWriter spreadsheet must have a corresponding Format object. It isn’t possible to use a Format with a write() method and then redefine it for use at a later stage. This is because a Format is applied to a cell not in its current state but in its final state. Consider the following example:

cell_format = workbook.add_format({'bold': True, 'font_color': 'red'})
worksheet.write('A1', 'Cell A1', cell_format)

# Later...
cell_format.set_font_color('green')
worksheet.write('B1', 'Cell B1', cell_format)

Cell A1 is assigned a format which initially has the font set to the color red. However, the color is subsequently set to green. When Excel displays Cell A1 it will display the final state of the Format which in this case will be the color green.