Sometimes, we want to save a new sheet in an existing Excel file using Pandas in Python.
In this article, we’ll look at how to save a new sheet in an existing Excel file using Pandas in Python.
How to save a new sheet in an existing Excel file using Pandas in Python?
To save a new sheet in an existing Excel file using Pandas in Python, we can use the pd.ExcelWriter
class.
For instance, we write:
import pandas as pd
import numpy as np
path = "data.xlsx"
x1 = np.random.randn(100, 2)
df1 = pd.DataFrame(x1)
x2 = np.random.randn(100, 2)
df2 = pd.DataFrame(x2)
writer = pd.ExcelWriter(path, engine = 'xlsxwriter')
df1.to_excel(writer, sheet_name = 'x1')
df2.to_excel(writer, sheet_name = 'x2')
writer.save()
writer.close()
We create 2 data frames with pd.DataFrame
.
Then we use the pd.ExcelWriter
class with the path and
engineto create the
writer` object to write the data to an Excel file.
We install Xlsxwriter
by running:
pip install XlsxWriter
to use 'xlsxwriter'
as the engine.
Next, we call “ on the data frames with writer
and the sheet_name
value to write the data frames into their own sheets.
Finally, we call writer.save
to save the Excel file and writer.close
to close the writer.
Now we should see the values in the data frames written into the spreadsheet file.
Conclusion
To save a new sheet in an existing Excel file using Pandas in Python, we can use the pd.ExcelWriter
class.