pandas:如何在导出到Excel后格式化单元格

我正在将一些pandas数据框导出到Excel中:

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

我知道我可以使用格式类: http : //xlsxwriter.readthedocs.org/format.html格式单元格,因为我把它们写入Excel。 但是,我不知道单元格写入Excel 之后应用格式样式的方法。 例如,如何设置为粗体和水平alignment到我已经导出到Excel的dataframne的行= 2和列= 3中的项目?

它应该是这样的:

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

根据需要添加到XLSXwriter的apply_style()

 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)