I have code from the time that I am reusing for a new task. The challenge is to write a new DataFrame to a new sheet into an existing excel file. But there is one part of the code that I donβt understand, but that just makes the code βworkβ.
working:
from openpyxl import load_workbook
import pandas as pd
file = r'YOUR_PATH_TO_EXCEL_HERE'
df1 = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
book = load_workbook(file)
writer = pd.ExcelWriter(file, engine='openpyxl')
writer.book = book
df1.to_excel(writer, sheet_name='New', index=None)
writer.save()
A small line writer.book=bookpuzzled me. Without this piece of code, the Excel file will delete all other sheets, with the exception of the sheet used in parameter sheetname=c df1.to_excel.
I looked through the documentation xlsxwriteras well openpyxl, but it may not seem like why this line gives me the expected result. Any ideas?
edit: I believe this post from where I got the original idea.