4

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?

2
  • 1
    Why don't you use the formatting before writing to Excel? Commented Jan 18, 2016 at 15:06
  • Because I need to format only certain rows and only certain columns of the dataframe which is output to Excel in one go with df.to_excel(writer,sheet) as above Commented Jan 18, 2016 at 15:13

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

I'm confused: do you mean you have modified the classes of XLSxwriter so as to add apply_style() ? I couldn't find apply_style documented anywhere.
Yes, you need to add this func to your XLSXwriter.
Is it possible to set_bg_color a range of cells rather than whole column?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.