获取AttributeError“Workbook”对象没有属性“add_worksheet” - 将数据框写入Excel工作表

时间:2018-03-27 18:07:00

标签: excel pandas openpyxl

我有以下代码,并尝试将数据框写入Excel文件的“现有”工作表(此处称为test.xlsx)。 Sheet3是目标工作表,我想放置数据,我不想用新的工作表替换整个工作表。

df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
book = load_workbook('test.xlsx')
writer = pd.ExcelWriter('test.xlsx')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets) # *I am not sure what is happening in this line*
df.to_excel(writer,"Sheet3",startcol=0, startrow=20)

当我逐行运行代码时,我收到最后一行的错误:

AttributeError:'Workbook'对象没有属性'add_worksheet'。现在,为什么我在不尝试添加工作表时会看到此错误?

注意:我知道这个类似的问题Python How to use ExcelWriter to write into an existing worksheet,但它不适合我,我也不能评论该帖子。

3 个答案:

答案 0 :(得分:1)

在创建openpyxl的实例时,您可以使用pd.ExcelWriter作为引擎。

import pandas as pd
import openpyxl

df1 = pd.DataFrame({'A':[1, 2, -3],'B':[1,2,6]})
book = openpyxl.load_workbook('examples/ex1.xlsx') #Already existing workbook
writer = pd.ExcelWriter('examples/ex1.xlsx', engine='openpyxl') #Using openpyxl

#Migrating the already existing worksheets to writer
writer.book = book
writer.sheets = {x.title: x for x in book.worksheets}

df1.to_excel(writer, sheet_name='sheet4')
writer.save()

希望这适合你。

答案 1 :(得分:1)

这是辅助函数:

def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
                       truncate_sheet=False, 
                       **to_excel_kwargs):
    """
    Append a DataFrame [df] to existing Excel file [filename]
    into [sheet_name] Sheet.
    If [filename] doesn't exist, then this function will create it.

    Parameters:
      filename : File path or existing ExcelWriter
                 (Example: '/path/to/file.xlsx')
      df : dataframe to save to workbook
      sheet_name : Name of sheet which will contain DataFrame.
                   (default: 'Sheet1')
      startrow : upper left cell row to dump data frame.
                 Per default (startrow=None) calculate the last row
                 in the existing DF and write to the next row...
      truncate_sheet : truncate (remove and recreate) [sheet_name]
                       before writing DataFrame to Excel file
      to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()`
                        [can be dictionary]

    Returns: None
    """
    from openpyxl import load_workbook

    # ignore [engine] parameter if it was passed
    if 'engine' in to_excel_kwargs:
        to_excel_kwargs.pop('engine')

    writer = pd.ExcelWriter(filename, engine='openpyxl')

    try:
        # try to open an existing workbook
        writer.book = load_workbook(filename)

        # get the last row in the existing Excel sheet
        # if it was not specified explicitly
        if startrow is None and sheet_name in writer.book.sheetnames:
            startrow = writer.book[sheet_name].max_row

        # truncate sheet
        if truncate_sheet and sheet_name in writer.book.sheetnames:
            # index of [sheet_name] sheet
            idx = writer.book.sheetnames.index(sheet_name)
            # remove [sheet_name]
            writer.book.remove(writer.book.worksheets[idx])
            # create an empty sheet [sheet_name] using old index
            writer.book.create_sheet(sheet_name, idx)

        # copy existing sheets
        writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
    except FileNotFoundError:
        # file does not exist yet, we will create it
        pass

    if startrow is None:
        startrow = 0

    # write out the new sheet
    df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)

    # save the workbook
    writer.save()

用法:

append_df_to_excel('test.xlsx', df, sheet_name="Sheet3", startcol=0, startrow=20)

一些细节:

**to_excel_kwargs - 用于将其他命名的参数传递给df.to_excel(),就像我在上面的示例中所做的那样 - {{1}未知参数startcol所以它将被视为append_df_to_excel()参数(字典)的一部分。

**to_excel_kwargs用于将现有工作表复制到writer.sheets = {ws.title:ws for ws in writer.book.worksheets} openpyxl对象。我无法解释为什么在阅读writer时没有自动完成 - 您应该向writer = pd.ExcelWriter(filename, engine='openpyxl')模块的作者询问有关...

答案 2 :(得分:0)

openpyxl支持Pandas数据帧,因此您最好直接使用它。有关详细信息,请参阅http://openpyxl.readthedocs.io/en/latest/pandas.html