Python 熊猫:导出到Excel后如何设置单元格格式

Python 熊猫:导出到Excel后如何设置单元格格式,python,excel,pandas,Python,Excel,Pandas,我正在将一些数据帧导出到Excel: df.to_excel(writer, sheet) wb = writer.book ws = writer.sheets[sheet] ws.write(1, 4, "DataFrame contains ...") writer.save() 我知道我可以使用format类:在将单元格写入Excel时对其进行格式化。但是,在单元格已写入Excel之后,我无法找到应用格式样式的方法。例如,如何将我导出到Excel的数据框的第2行和第3列中的项目设置为粗

我正在将一些数据帧导出到Excel:

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

我知道我可以使用format类:在将单元格写入Excel时对其进行格式化。但是,在单元格已写入Excel之后,我无法找到应用格式样式的方法。例如,如何将我导出到Excel的数据框的第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)

为什么不在写入Excel之前使用格式设置?因为我只需要格式化数据框中的某些行和某些列,然后使用df一次性输出到Excel。如上所述,我很困惑:你是说你修改了XLSxwriter的类以便添加apply_style()?我在任何地方都找不到“应用样式”文档。是的,您需要将此func添加到XLSXwriter中。是否可以将“应用样式”设置为一个单元格范围而不是整个列的颜色?