【问题标题】:Getting AttributeError 'Workbook' object has no attribute 'add_worksheet' - while writing data frame to excel sheet获取 AttributeError 'Workbook' 对象没有属性 'add_worksheet' - 在将数据框写入 Excel 工作表时
【发布时间】:2018-09-06 06:20:57
【问题描述】:

我有以下代码,我正在尝试将数据框写入 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:“工作簿”对象没有属性“add_worksheet”。现在,当我不尝试添加工作表时,为什么会看到此错误?

注意:我知道Python How to use ExcelWriter to write into an existing worksheet 有类似的问题,但它对我不起作用,我也无法评论该帖子。

【问题讨论】:

  • 这很可能是由于您不知道发生了什么的代码。为什么你需要那个?
  • 我们需要 book 和 sheet 属性来添加工作表或保存到 Excel。 'writer.book = book' 将 load_book 的结果设置为 writer 的 book 属性,以便您可以对其进行操作。 'writer.sheets = dict((ws.title, ws) for ws in book.worksheets)' - 此行生成 sheet 属性。我认为这是必要的,以便我们可以编辑目标工作表。
  • 您试过一次循环一张纸吗?我过去成功地做到了这一点
  • 我没有。你打算怎么做?我对 python 很陌生——如果你能用一些有用的代码来详细说明一下
  • Pandas 默认使用 xlsxwriter。您需要明确将引擎设置为 openpyxl。

标签: excel pandas openpyxl


【解决方案1】:

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

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()

希望这对你有用。

【讨论】:

  • 您好,感谢您的帮助。我试过这段代码。它不是添加到 'Sheet3' ,而是创建 'Sheet31' 并将数据框放在那里 - 'df1.to_excel(writer, sheet_name='sheet3', startcol=0, startrow=20, index = 0)' 。但我希望它在 Sheet3 中写入而不是创建一个新的。
【解决方案2】:

可以使用append_df_to_excel()辅助函数,即defined in this answer

用法:

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

一些细节:

**to_excel_kwargs - 用于将额外的 named 参数传递给 df.to_excel(),就像我在上面的示例中所做的一样 - append_df_to_excel() 不知道参数 startcol,因此它将被视为**to_excel_kwargs 参数的一部分(字典)。

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

【讨论】:

  • 嘿,非常感谢,这行得通。我在你的代码中看到了两个很大的不同: 1. df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs) 你能解释一下这个参数 **to_excel_kwargs - 我没有使用这个吗? 2. writer = pd.ExcelWriter(filename, engine='openpyxl') 使用openpyxl作为引擎。此外,如果您也可以解释这一行 - 那将有很大帮助 - writer.sheets = dict( (ws.title, ws) for ws in writer.book.worksheets)
【解决方案3】:

openpyxl 支持 Pandas 数据帧,因此您最好直接使用它。详情请见http://openpyxl.readthedocs.io/en/latest/pandas.html

【讨论】:

    【解决方案4】:

    基于https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_excel.html

    这确实对我有用(熊猫版本 1.3.5)

    import pandas as pd
    df1 = pd.DataFrame({'a':[0,1,2], 'b':[1,2,3],'c':[2,3,4]})
    df2 = pd.DataFrame({'aa':[10,11,12], 'bb':[11,12,13],'cc':[12,13,14]})
    
    with pd.ExcelWriter('test.xlsx') as writer:
        for i, df in enumerate([df1, df2]):
            df.to_excel(writer,sheet_name=f'sheet_{i}', index=False)
    

    【讨论】:

      猜你喜欢
      • 2018-05-26
      • 1970-01-01
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      • 2020-09-30
      • 2019-11-03
      • 2022-11-03
      • 1970-01-01
      相关资源
      最近更新 更多