Pandas df.to_excel for multiple dfs?

Viewed 74

So I want to save 2 dataframes into 2 different worksheets, but the same file. My code for this part is:

df.to_excel(path, sheet name = 'sheet1')
df2.to_excel(path, sheet name = 'sheet2')

And for some reason the code ignores the first part, the excel file only has sheet2 with df2 on it, sheet1 is nowhere to be found. Before I added the df2 part the code saved the df perfectly fine. Why is that, how could I fix this?

1 Answers

You can use a writer for this:

with pd.ExcelWriter(output_file) as writer:
    for i,df in enumerate(list_of_dfs, start=1):
        df.to_excel(writer, sheet_name= 'sheet'+str(i))

    writer.save()
Related