Home » excel » python – How to export dfs to excel with multiple sheets and different sheet names pandas

python – How to export dfs to excel with multiple sheets and different sheet names pandas

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to iterate through student ID’s WITH A LOOP by printing a df to a sheet in excel and having the student ID be the tab name.

In other words:

df to excel and tab name is 1

next df to new sheet and tab name is 2

iterate through all student IDs

final=[dataframe,dataframe,dataframe]
studentIDs=[1,2,3]


writer = pd.ExcelWriter('Name.xlsx', engine='xlsxwriter')
for df in final:
        df.to_excel(writer, sheet_name='%s' %studentIDs)
        writer.save()
How to&Answers:
final=[dataframe,dataframe,dataframe] 

studentIDs=[1,2,3]


writer = pd.ExcelWriter('Name.xlsx', engine='xlsxwriter')
for i,df in enumerate(final, 0):
    df.to_excel(writer, sheet_name='%s' %studentIDs[i])

 writer.save()

If the lists will always match in order, then you can use enumerate (which gives you a list starting from that index onward) and then match it up to the list above, but I would recommend using a dictionary

final = {
   1 : dataframe,
   2 : dataframe,
   3 : dataframe
}


writer = pd.ExcelWriter('Name.xlsx', engine='xlsxwriter')
for sheet_name in final:
    final[sheet_name].to_excel(writer, sheet_name= str(sheet_name))

writer.save()