Pandas: how to format cells after export to Excel

I export 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 that I can use the format class: http://xlsxwriter.readthedocs.org/format.html to format cells when I write them in Excel. However, I cannot find a way to apply the formatting style after the cells have already been written to Excel. For example. how to set in bold and horizontally center the element in row = 2 and column = 3 of the data file that I exported to Excel?

+4
source share
1 answer

It should look like this:

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

apply_style(), 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)

:

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

Source: https://habr.com/ru/post/1624804/


All Articles