python – 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后,我无法找到应用格式样式的方法.例如.如何设置为粗体并水平对齐中心,我已导出到Excel的dataframne的row = 2和column = 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)
点赞