Scenario:
- Read an excel file with multiple sheets
- For each sheet at input read a few specific columns and manipulate the existing data
- Create an output dataframe
- Save this dataframe in one existing output file as a new sheet
Below is the snippet of my code:
for sheet in all_sheets: # all_sheets is the list of sheets from the input file
print(sheet) # Here i transform the data but removed the
writer = pd.ExcelWriter('Output.xlsx', engine='xlsxwriter')
df_final_4.to_excel(writer, sheet_name=sheet, index=True)
writer.save()
Problem Statement:
- The file is written with only one sheet which contains the data for the last iteration.
- The previous iteration gets overwritten and only one sheet remains in the output file.
- I have tried multiple approches but each yeild the same result.
Can anyone please guide me where i am going wrong?
Other approches:
for sheet in all_sheets:
writer = pd.ExcelWriter('Output.xlsx', engine='xlsxwriter')
df_final_4.to_excel(writer, sheet_name=sheet, encoding='utf-8', index=True)
writer.save()
for sheet in all_sheets[8:10]:
print(sheet)
writer = pd.ExcelWriter('newfile.xlsx', engine='xlsxwriter')
df_final_4.to_excel(writer, sheet_name=sheet, index=True)
writer.save()
wb = openpyxl.Workbook()
wb.save('Output.xlsx')
book = load_workbook('Output.xlsx')
writer = pd.ExcelWriter('Output.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df_final_4.to_excel(writer, sheet, index=True)
writer.save()
writer.close()