Pandas to_excel() – can't figure out how to export multiple dataframes as different sheets in one excel using for loop

Question:

there are many similar questions to this. I have looked through them all and I can’t figure out how to fix my issue.

I have 11 dataframes. I would like to export all of these dataframes to one excel file, with one sheet per data frame. I have 2 lists: One is a list of dataframe objects, and one is a list of the names I want for each df. the lists are each ordered so that if you iterated through each list at the same time it would be the df and the df name I want.

Here is my code:

for (df, df_name) in zip(df_list, df_name_list):
    sheetname = "{}".format(df_name)
    df.to_excel(r"myfoldermyfile.xlsx", index=False, sheet_name=sheetname)

It exports to excel, but it appears to overwrite the sheet each time. The final sheet has the same name as the final dataframe, so it looped through both lists but it won’t save separate sheets. Any help would be much appreciated!

UPDATE – ISSUE FIXED – EDITING TO ADD THE CODE THAT WORKED

`with pd.ExcelWriter(r"myfoldermyfile.xlsx") as writer:
for (df, df_name) in zip(df_list, df_name_list):
sheetname = "{}".format(df_name)
df.to_excel(writer, sheet_name=sheetname)’

Asked By: Ivy McKee

||

Answers:

I just tried something based docs example as it seems to work ok see:

import pandas as pd

data = [(f'Sheet {j}', pd.DataFrame({'a': [i for i in range(20)], 'b': [j for i in range(20)] })) for j in range(10)]

with pd.ExcelWriter('output.xlsx') as writer:
    for sheet, df in data:
        df.to_excel(writer, sheet_name=sheet)
Answered By: John M.