Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Pandas to write to excel sheets in specified order

At the end of Pandas .to_excel documentation it shows how to write sheets in order:

>>> writer = pd.ExcelWriter('output.xlsx')
>>> df1.to_excel(writer,'Sheet1')
>>> df2.to_excel(writer,'Sheet2')
>>> writer.save()

Is there a way for me to write to sheet2 first, then sheet1, in my python program. However, I still need the sheet1 to appear before sheet2 in the final excel file?

like image 395
Zhang18 Avatar asked Oct 24 '25 19:10

Zhang18


1 Answers

As jmcnamara wrote, it's not advisable to change the order of sheets because of Excel's internal structure, but you can change which sheet is active when the Excel file opens using activate():

>>> writer = pd.ExcelWriter('output.xlsx')
>>> df1.to_excel(writer,'Sheet1')
>>> df2.to_excel(writer,'Summary')
>>> writer.sheets['Summary'].activate()
>>> writer.save()

When you open the Excel file, the sheet called "Summary" will be displayed, although "Sheet1" will still be the first sheet.

like image 62
Nathaniel Jones Avatar answered Oct 26 '25 08:10

Nathaniel Jones