简体   繁体   中英

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

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()
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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM