简体   繁体   English

将pandas read_excel生成的dict保存到多表excel文件

[英]Saving dict generated by pandas read_excel to multi-sheet excel file

Pandas' read_excel() method when called with sheet_name=None will return a dict with each excel sheet.当使用sheet_name=None调用 Pandas 的read_excel()方法时,每个 Excel 工作表都会返回一个字典。 How can I reverse this operation, ie take a dict and save a multi-sheet excel file?如何反转此操作,即使用字典并保存多页excel文件? I'm only seeing a way to save a single dateframe to excel via the to_excel() method.我只看到了一种通过to_excel()方法将单个日期框保存到 excel 的方法。

I would say that generally this operation is performed using pandas.ExcelWriter (suppose df_dict is your dictionary with DataFrames):我会说通常这个操作是使用pandas.ExcelWriter执行的(假设 df_dict 是你的 DataFrames 字典):

import pandas as pd
with pd.ExcelWriter('path/to/save/table.xlsx') as writer:
    for key, df in df_dict.items(): 
        df.to_excel(writer, key)
    writer.save()

Documentation link 文档链接

If I understand you correctly, you'll need to use a class called ExcelWriter , theres a cool example on their docs :如果我理解正确,您将需要使用一个名为ExcelWriter的类,他们的文档中有一个很酷的示例:

df1 = pd.DataFrame([["AAA", "BBB"]], columns=["Spam", "Egg"])
df2 = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"])
with ExcelWriter("path_to_file.xlsx") as writer:
    df1.to_excel(writer, sheet_name="Sheet1")
    df2.to_excel(writer, sheet_name="Sheet2")

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

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