Search code examples
pythondatabasedictionarytabsexport-to-excel

Python export a dictionary with datasets to different tabs in excel


I have a dictionary composed of several dataframes

dictionary = ({'df1':Dataframe, 'df2':Dataframe, 'df3':Dataframe, 'df4':Dataframe, 'df5':Dataframe})

I would like to export the dictionary to an excel file where every dictionary is in a different tab and of course the key name should be written somewhere to distinguish between them.

Any suggestion would be really helpful! Thank you!


Solution

  • You can write multiple sheets in an Excel file using pandas (see example at the bottom):

    import pandas as pd
    with pd.ExcelWriter('output.xlsx') as writer:
        df1.to_excel(writer, sheet_name='Sheet_name_1')
        df2.to_excel(writer, sheet_name='Sheet_name_2')
    

    Instead of writing df1/df2/... explicitly you can simply loop over your dictionary of data frames:

    import pandas as pd
    with pd.ExcelWriter('output.xlsx') as writer:
        for key, val in dictionary.items():
            val.to_excel(writer, sheet_name=key)