If we want to create a new Excel file , And will DataFrame Add to Excel The worksheet for is simple .
import pandas as pd
import numpy as np
df1=pd.DataFrame(np.arange(7))
df2=pd.DataFrame(np.arange(7))
writer=pd.ExcelWriter("Excel.xlsx")
df1.to_excel(writer,"first") #first Is the name of the first worksheet
df2.to_excel(writer,"second") #second Is the name of the second worksheet
writer.save()
But if one already exists Excel file , If we use the above code, we will overwrite the contents of the original file , That is to delete the original data , The new code looks like this :
import pandas as pd
from openpyxl import load_workbook
book = load_workbook('Excel.xlsx')
writer=pd.ExcelWriter("Excel.xlsx",engine='openpyxl')
writer.book = book
df1.to_excel(writer,"first")
df2.to_excel(writer,"second")
writer.save()
The last attached Github The official answer :pandas How to in the existing Excel New sheet on table ?