Search code examples
pythondataframexlsxwriter

Can't export multiple DataFrames to different sheets in Excel using XlsxWriter


I am using XlsxWriter, and trying to export 2 DFs to 2 different Sheets in Excel. I followed this link. But it doesn't work for me. Let me illustrate:

# Create a Pandas Excel writer using XlsxWriter as the engine.
df1 = pd.DataFrame({'A':[1,2,3],'B':[7,8,9]})
df2 = pd.DataFrame({'A':[1,2,3],'C':['AA','BB','CC']})

writer = pd.ExcelWriter(os.path.join(path,'Output.xlsx'), engine='xlsxwriter')
df1.to_excel(writer, sheet_name='Sheet1', index=False)
writer.save()
df2.to_excel(writer, sheet_name='Sheet2', index=False)
writer.save()

In Output.xlsx I can only see Sheet1 corresponding to df1, but not Sheet2.

Output:

enter image description here

But, if I would have used engine as openpyxl instead of xlsxwriter, I can see both the dfs exported into Sheet1 & Sheet2.

I think, there is a small tweak, but can't figure it out.


Solution

  • Remove writer.save(). Calling to_excel has already saved the data.

    The to_excel docs explain you only need to use a different sheet name to save to different sheets.

    Multiple sheets may be written to by specifying unique sheet_name.

    This is shown in the doc examples too:

    df2 = df1.copy()
    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')