首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >熊猫附加excel(xlsx)文件给attribute.error

熊猫附加excel(xlsx)文件给attribute.error
EN

Stack Overflow用户
提问于 2022-10-16 08:40:10
回答 1查看 663关注 0票数 0

因任何一个错误而陷入麻烦;writer.book=bookAttributeError: can't set attribute 'book'BadZipFile

对于没有出现badzipfile错误的代码,我把写excel文件的代码行放在第一位,dataOutput=pd.DataFrame(dictDataOutput,index=[0]),但是,即使我不能摆脱writer.book = book AttributeError: can't set attribute 'book'作为其中之一,所以答案建议我需要将openpyxl带回到以前的版本,或者使用CSV文件而不是excel。我觉得这不是解决办法。应该有我无法进入的解决办法

代码语言:javascript
运行
复制
dataOutput=pd.DataFrame(dictDataOutput,index=[0])
dataOutput.to_excel('output.xlsx') 'output.xlsm'
book = load_workbook('output.xlsx') 'output.xlsm'
writer = pd.ExcelWriter('output.xlsx')OR'output.xlsm'#,engine='openpyxl',mode='a',if_sheet_exists='overlay')
writer.book = book
writer.sheets = {ws.title: ws for ws in book.worksheets}

for sheetname in writer.sheets:
    dataOutput.to_excel(writer,sheet_name=sheetname, startrow=writer.sheets[sheetname].max_row, index = False,header= False)

writer.save()

我在在这里输入链接描述中寻找答案,在在这里输入链接描述中寻找attributeError的详细解决方案。

-我试过另一种方法

代码语言:javascript
运行
复制
with pd.ExcelWriter('output.xlsx', mode='a',if_sheet_exists='overlay') as writer:
    dataOutput.to_excel(writer, sheet_name='Sheet1')
    writer.save()

但这次又犯了一个错误

代码语言:javascript
运行
复制
FutureWarning: save is not part of the public API, usage can give in unexpected results and will be removed in a future version

writer.save()

在@Andrew的评论之后,我用这种方式高呼我的代码;

代码语言:javascript
运行
复制
with pd.ExcelWriter('outputData.xlsm', engine='openpyxl', mode='a', if_sheet_exists='overlay') as writer:
    book = load_workbook('outputData.xlsm', keep_vba=True)

    writer.book = book
    writer.sheets = {ws.title: ws for ws in book.worksheets}
    current_sheet = book['Sheet1']
    Column_A = current_sheet['A']
    maxrow = max(c.row for c in Column_A if c.value is not None)

    for sheetname in writer.sheets:
        AllDataOutput.to_excel(writer, sheet_name=sheetname, startrow=maxrow, index=False, header=False)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-19 05:37:49

你的问题有些不清楚,但我会尽力回答我认为你想做的事情。

首先,一些不起作用的事情:

  1. to_excel文档中,“如果希望写入工作簿中的多个工作表,就必须指定一个ExcelWriter对象”,因此在运行dataOutput.to_excel('output.xslx')时,您将创建一个只有一个工作表的excel工作簿。稍后,您似乎正在尝试编写多个工作表,但是您只能编写一个工作表,因为这是工作簿中的全部内容。
  2. ExcelWriter文档中,不推荐使用.save(),而应该使用.close()。但是建议使用上下文管理器(with ... as ... :),这样您就可以完全避免这样做了。
  3. 默认情况下,ExcelWriter使用w (写)模式,因此您之前遇到的BadZipFile错误很可能与运行的顺序有关。如果您用to_excel编写了一本书,然后用openpyxl加载它,然后使用ExcelWriter,您将编写、加载,然后立即用一个空白的文件覆盖文件。如果您再次尝试加载书籍而不使用to_excel重新创建它,那么您将尝试加载一个空文件,这就是抛出该错误的原因。

您在问题中链接到的答案似乎使用了一个更老的pandas版本,并且围绕着与Excel文件的交互行为有了很大的不同。最新的版本似乎简化了很多事情!

作为示例解决方案,我将假设您有两个名为df1df2df1df2,您希望在output.xlsx中写入Sheet_1Sheet_2,并且希望用名为df3df4的附加DataFrames更新这些表中的数据(使用overlay选项)。为了确认,我已经安装了openpyxl = 3.0.10pandas = 1.5.0

正如您目前所写的一样,dataOutput中没有任何将反映在output.xslx中的更新,但我将创建一个名为df_dict的字典,它可以保存DataFrames并根据应该写入的表单进行更新。我相信您可以调整,以适应您的需要,使用任何您喜欢的数据结构!

代码语言:javascript
运行
复制
df1 = pd.DataFrame(data = {'A': ['a', 'b', 'c'], 'B': ['g','h','i']})
df2 = pd.DataFrame(data = {'C': ['o', 'p', 'q'], 'D': ['u','v','w']})

df_dict = {'Sheet_1': df1, 'Sheet_2': df2}

with pd.ExcelWriter('output.xlsx') as writer:
    for sheetname, dfname in df_dict.items():
        dfname.to_excel(writer, sheet_name = sheetname)

# Updated data is put in DataFrames
df3 = pd.DataFrame(data = {'A': ['a', 'b', 'c', 'd', 'e', 'f'], 'B': ['g', 'h', 'i', 'j', 'k', 'l']})
df4 = pd.DataFrame(data = {'C': ['o', 'p', 'q', 'r', 's', 't'], 'D': ['u', 'v', 'w', 'x', 'y', 'z']})

# df_dict is updated with the new DataFrames
df_dict = {`Sheet_1`: df3, 'Sheet_2': df4}

# This block now uses the name of the sheet from the workbook itself to get the updated data.
# You could also just run the same block as above and it would work.
with pd.ExcelWriter('output.xlsx', mode = 'a', if_sheet_exists = 'overlay') as writer:
    for sheet in writer.sheets:
        df_dict[sheet].to_excel(writer, sheet_name = sheet)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74085655

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档