【问题标题】:pandas: how to format cells after exporting to Excelpandas:导出到 Excel 后如何格式化单元格
【发布时间】:2016-04-23 19:22:16
【问题描述】:

我正在将一些 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 的数据帧的行 = 2 和列 = 3 中的项目设置为粗体并水平对齐到中心?

【问题讨论】:

  • 为什么在写入 Excel 之前不使用格式?
  • 因为我只需要格式化数据帧的某些行和某些列,这些数据帧与上面的 df.to_excel(writer,sheet) 一起输出到 Excel

标签: python excel pandas


【解决方案1】:

应该是这样的:

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

根据apply_style()需要添加到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)

或者你可以这样写:

new_style = wb.add_format().set_bold().set_align('center')
ws.write(2, 3, ws.written_cells[sheet].get('C2), new_style)

【讨论】:

  • 我很困惑:你的意思是你已经修改了 XLSxwriter 的类以添加 apply_style() ?我在任何地方都找不到 apply_style 文档。
  • 是的,您需要将此功能添加到您的 XLSXwriter。
  • 是否可以设置_bg_color 一系列单元格而不是整个列?
猜你喜欢
  • 1970-01-01
  • 2017-02-22
  • 2017-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多