dhananya s
dhananya s

Reputation: 11

writing multiple excel sheets into one for loop code

sheet1=[FC_filter1,FC_filter2,FC_filter3]

with pd.ExcelWriter(path, mode='a', if_sheet_exists='replace', engine="openpyxl") as writer:
    FC_filter1.to_excel(writer, sheet_name='FC_filter1',index='False')
    FC_filter2.to_excel(writer, sheet_name='FC_filter2',index='False')
    FC_filter3.to_excel(writer, sheet_name='FC_filter3',index='False')

Can we make this code into one line using for loop instead of mentioning FC_filter1,2,3 each time ?

Upvotes: 0

Views: 34

Answers (1)

Rabinzel
Rabinzel

Reputation: 7903

Use a loop through sheet1 with enumerate to name the sheets counting up, starting by 1. This assumes that the names of your filter going like 1,2,3,... If not, you could save the data as dictionary with the name as key (string) and the df as value and access them in a for loop.

sheet1=[FC_filter1,FC_filter2,FC_filter3]

with pd.ExcelWriter(path, mode='a', if_sheet_exists='replace', engine="openpyxl") as writer:
    for i, fc in enumerate(sheet1, 1):
        fc.to_excel(writer, sheet_name=f'FC_filter{i}',index='False')

Upvotes: 1

Related Questions