簡體   English   中英

pandas:導出到Excel后如何格式化單元格

[英]pandas: how to format cells after exporting to 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM