简体   繁体   English

Python如何将数据框导出到xlsx中的两个选项卡

[英]Python how to export dataframes to two tabs in xlsx

I want to export dataframe C to an existing excel, saving it in a new tab.我想将数据框 C 导出到现有的 excel,并将其保存在新选项卡中。 I tried:我试过:

writer=pd.ExcelWriter(r'H:\test.xlsx', engine='xlsxwriter')
C.to_excel(writer,sheet_name='c') 
writer.save()

(Notice: Excel test is an existing and previously saved Excel, with different tables A, B in tabs a, b, which I want to keep) (注意:Excel 测试是一个现有的和以前保存的 Excel,在标签 a、b 中有不同的表 A、B,我想保留这些)

This code however deletes the existing excel and creates a new one with only the tab "c".但是,此代码会删除现有的 excel 并创建一个只有选项卡“c”的新 Excel。 I want to keep the existing tabs "a" and "b".我想保留现有的标签“a”和“b”。

What is the right way?什么是正确的方法?

ps: I tried suggestion on link "How to save a new sheet in an existing excel file, using Pandas? " as follows: ps:我尝试了有关“如何使用 Pandas 在现有 excel 文件中保存新工作表?”链接的建议,如下所示:

writer=pd.ExcelWriter(r'H:\C.xlsx', engine='xlsxwriter')
y_pred_all2.to_excel(writer,sheet_name='cc')
writer.save()
writer.close()
from openpyxl import load_workbook
path=r'H:\C.xlsx'
book=load_workbook(path)
writer=pd.ExcelWriter(path, engine='xlsxwriter')
writer.book=book
C.to_excel(writer,sheet_name='returns') 

This gives me error: AttributeError: 'Workbook' object has no attribute 'add_worksheet'这给了我错误:AttributeError: 'Workbook' object has no attribute 'add_worksheet'

According to this answer this is a limitation in the xlsxwriter engine.根据这个答案,这是 xlsxwriter 引擎的一个限制。 The pandas docs show the default for ExcelWriter is to use openpyxl which should be able to do what you are looking for. pandas 文档显示 ExcelWriter 的默认值是使用 openpyxl,它应该能够做你正在寻找的。 If you want to be explicit about the engine being used, this should work:如果你想明确使用的引擎,这应该有效:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM