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

时间:2016-01-18 15:03:41

标签: python excel pandas

我正在将一些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中的项目设置为粗体并水平对齐?

1 个答案:

答案 0 :(得分:1)

它应该是这样的:

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)