python – 使用Openpyxl与现有工作簿的Pandas Excel Writer

我有一段时间的代码,我正在重新使用新任务.任务是将新的DataFrame写入新工作表中,并将其写入现有的excel文件中.但是有一部分代码我不明白,但它只是使代码“工作”.

工作:

from openpyxl import load_workbook
import pandas as pd
file = r'YOUR_PATH_TO_EXCEL_HERE'

df1 = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
book = load_workbook(file)
writer = pd.ExcelWriter(file, engine='openpyxl')
writer.book = book # <---------------------------- piece i do not understand
df1.to_excel(writer, sheet_name='New', index=None)
writer.save()

writer.book = book的小行让我难过.如果没有这段代码,Excel文件将删除除df1.to_excel中sheetname =参数中使用的工作表之外的所有其他工作表.

我查看了xlsxwriter‘s文档以及openpyxl‘s,但似乎无法弄清楚为什么该行给了我预期的输出.有任何想法吗?

编辑:我相信this post是我从原来的想法.

最佳答案 在ExcelWriter的源代码中,使用openpyxl,它初始化空工作簿并删除所有工作表.这就是你需要明确添加它的原因

class _OpenpyxlWriter(ExcelWriter):
    engine = 'openpyxl'
    supported_extensions = ('.xlsx', '.xlsm')

    def __init__(self, path, engine=None, **engine_kwargs):
        # Use the openpyxl module as the Excel writer.
        from openpyxl.workbook import Workbook

        super(_OpenpyxlWriter, self).__init__(path, **engine_kwargs)

        # Create workbook object with default optimized_write=True.
        self.book = Workbook()

        # Openpyxl 1.6.1 adds a dummy sheet. We remove it.
        if self.book.worksheets:
            try:
                self.book.remove(self.book.worksheets[0])
            except AttributeError:

                # compat
                self.book.remove_sheet(self.book.worksheets[0])
点赞