I have two spreadsheet in '.xls' format, both have two sheets (sheet1 and sheet2). I am trying to overwrite the 'sheet2' in book2.xls with 'sheet2' from book1.xls. I am trying the pandas approach and here is my draft code,
import pandas as pd
# Open the first spreadsheet
df1 = pd.read_excel('Book1.xls', sheet_name='sheet2')
# Specify the writer file
writer = pd.ExcelWriter('Book2.xls')
# Write output
df1.to_excel(writer, 'sheet2', engine='xlswriter', index=False)
writer.save()
After merging, I expect only the 'sheet2' in book2.xls to be updated while retaining the 'sheet1'. However, thats not the case and book2.xls now only has 'sheet2' and deleted the 'sheet1'. I looked into several answers (e.g.,) and they work for '.xlsx' format using openpyxl
. I am looking for a solution that deals with '.xls' format. Thanks for your help.
Also, I would have hoped, pandas.ExcelWrite
to have one extra option for merging just a specified sheet, sigh!
****************************
Another approach I tried is here, but I get the error while merging the sheet.
import pandas as pd
# Open the first spreadsheet
df1 = pd.read_excel('Book1.xls')
excelBook = pd.ExcelFile(path+'Book2.xls')
writer = pd.ExcelWriter(path+'Book2.xls')
writer.book = excelBook
writer.sheets = dict((ws.title, ws) for ws in excelBook.sheet_names)
# Add new sheets
df1.to_excel(writer, "Sheet2", index=False)
# Save the file
writer.save()
`AttributeError: 'ExcelFile' object has no attribute 'add_sheet'`