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

Viewed 193

Pandas' read_excel() method when called with sheet_name=None will return a dict with each excel sheet. How can I reverse this operation, i.e. take a dict and save a multi-sheet excel file? I'm only seeing a way to save a single dateframe to excel via the to_excel() method.

2 Answers

I would say that generally this operation is performed using pandas.ExcelWriter (suppose df_dict is your dictionary with 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:

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")
    writer.save()
Related