Reputation: 8950
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. E.g. 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?
Upvotes: 4
Views: 2852
Reputation: 2849
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)
Upvotes: 1