简体   繁体   中英

pandas: how to format cells after exporting to Excel

I am exporting some pandas dataframes to Excel:

df.to_excel(writer, sheet)
wb = writer.book
ws = writer.sheets[sheet]
ws.write(1, 4, "DataFrame contains ...")
writer.save()

I understand I can use the format class: http://xlsxwriter.readthedocs.org/format.html to format cells as I write them to Excel. However, I can't figure out a way to apply a formatting style after cells have already been written to Excel. Eg how do I set to bold and horizontally align to the centre the item in row = 2 and column = 3 of the dataframne I have exported to Excel?

It should look like this:

new_style = wb.add_format().set_bold().set_align('center')
ws.apply_style(sheet, 'C2', new_style)

According to apply_style() that need to be added to XLSXwriter:

def apply_style(self, sheet_name, cell, cell_format_dict):
        """Apply style for any cell, with value or not. Overwrites cell with joined 
        cell_format_dict and existing format and with existing or blank value"""

        written_cell_data = self.written_cells[sheet_name].get(cell)
        if written_cell_data:
            existing_value, existing_cell_format_dict = self.written_cells[sheet_name][cell]
            updated_format = dict(existing_cell_format_dict or {}, **cell_format_dict)
        else:
            existing_value = None
            updated_format = cell_format_dict

        self.write_cell(sheet_name, cell, existing_value, updated_format)

OR you can write so:

new_style = wb.add_format().set_bold().set_align('center')
ws.write(2, 3, ws.written_cells[sheet].get('C2), new_style)

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