gpt4 book ai didi

python - XlsxWriter 中出现意外的单元格格式化行为

转载 作者:行者123 更新时间:2023-12-01 00:43:27 24 4
gpt4 key购买 nike

使用 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() 时开始。声明。

所以基本上,在执行 worksheet.merge_range('A1:G1', 'Font Size SHOULD be 14',fmt_title)< 期间,您的 fmt_title 格式化对象尚未真正“使用”/。仅存储对格式化对象的引用以供以后使用。

xlsxwriter documentation确认您所看到的是正常行为(尽管一开始这可能是违反直觉的):

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.

关于python - XlsxWriter 中出现意外的单元格格式化行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57171491/

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