简体   繁体   中英

Unexpected cell formatting behaviour in XlsxWriter

Using xlsxwriter for spreadsheet creation. Set up the format:

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

I applied the format to a merged row then changed the font-size (with the intent of writing another row with a smaller font size)

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)

Problem I am running into is after changing the font-size, all rows with the applied format change to a font-size of 12. Why does the format change AFTER i have written then row?

The key thing to realize is that writing of the actual excel file only starts upon execution of the workbook.close() statement.

So basically your fmt_title formatting object is not really 'used' yet during execution of worksheet.merge_range('A1:G1', 'Font Size SHOULD be 14',fmt_title) . Merely a reference to the formatting object is stored for later use.

The xlsxwriter documentation confirms that what you're seeing is normal behaviour (though admittedly it can be counter-intuitive at first):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM