How to write to an existing excel file without overwriting data (using pandas)?
excel, pandas, python, python-2.7
Solution
Pandas docs says it uses openpyxl for xlsx files. Quick look through the code in `ExcelWriter` gives a clue that something like this might work out:
import pandas
from openpyxl import load_workbook
book = load_workbook('Masterfile.xlsx')
writer = pandas.ExcelWriter('Masterfile.xlsx', engine='openpyxl')
writer.book = book
## ExcelWriter for some reason uses writer.sheets to access the sheet.
## If you leave it empty it will not know that sheet Main is already there
## and will create a new sheet.
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])
writer.save()
Problem
I use pandas to write to excel file in the following fashion: ``` import pandas writer = pandas.ExcelWriter('Masterfile.xlsx') data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2']) writer.save() ``` Masterfile.xlsx already consists of number of different tabs. However, it does not yet contain "Main". Pandas correctly writes to "Main" sheet, unfortunately it also deletes all other tabs.
Related problems
- Append existing excel sheet with new dataframe using python pandas
- File corruption while writing using Pandas
- How to write to an existing excel file without breaking formulas with openpyxl?
- openpyxl load_workbook() on a legit .xlsx file leads to a zipfile.BadZipFile error
- Writing Pandas DataFrame to Excel: How to auto-adjust column widths