Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python appending dataframe to exsiting excel file and sheet

I have a question about appending a dataframe to existing sheet on existing file.

I tried to write the code by myself

writer = pd.ExcelWriter('existingFile.xlsx', engine='openpyxl', mode='a')
df.to_excel(writer, sheet_name="existingSheet", startrow=writer.sheets["existingSheet"].max_row, index=False, header=False)

and this would cause an error

ValueError: Sheet 'existingSheet' already exists and if_sheet_exists is set to 'error'.

and I googled and found this function in here;

Append existing excel sheet with new dataframe using python pandas

and even with this function, it still causes the same error, even though i think this function prevents this exact error from what i think.

Could you please help?

Thank you very much!

like image 767
dkcloud9 Avatar asked Apr 13 '26 21:04

dkcloud9


1 Answers

I guess I am late to the party but

Add keyword if_sheet_exists='replace' to ExcelWriter like this

pd.ExcelWriter('existingFile.xlsx', engine='openpyxl', mode='a', if_sheet_exists='replace' )

Then you can use the latest version of pandas

like image 102
Mikk Avatar answered Apr 16 '26 11:04

Mikk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!