+1 vote
in Programming Languages by (73.6k points)
In the Excel file, I already have one sheet, "Sheet1". I want to add a new sheet, "Sheet 2," to the Excel file so that I can write data from a dataframe to the new sheet. How can I add a new sheet to an existing Excel file using Python?

1 Answer

+2 votes
by (355k points)
selected by
 
Best answer

The ExcelWriter() method of Pandas can be used to append a new sheet to an existing Excel file.

In the following example, I am adding a new sheet "Sheet 2" to tempfile.xlsx. Since tempfile.xlsx already exists, I am using append mode (mode='a') to write data from the dataframe to "Sheet 2".

import pandas as pd 

df = pd.DataFrame([['f',11], ['g',12]])

with pd.ExcelWriter("tempfile.xlsx", mode="a") as writer:

df.to_excel(writer, sheet_name="Sheet2", index=False, header=False)


...