Search code examples
excelpython-3.xpandaspandas-groupby

pandas writing to excel sheet deleting other sheets in file


I have simple code to export python dataframe to existing excel file with sheets but the writer keep deleting the existing sheet from the file

read = pd.ExcelFile('Saw_Load.xlsx')
print(read.sheet_names)
writer = pd.ExcelWriter('Saw_Load.xlsx')
result.to_excel(writer,'saw', index = False)
read2 = pd.ExcelFile('Saw_Load.xlsx')
print(read2.sheet_names)
writer.save()

Here is the output i am getting

['saw', 'Pivot']
['saw']

We can clearly see before to_excel function was used there were 2 sheets (saw,Pivot). After there is only one 'saw'

It could be a simple fix in formula but couldn't seem to find anything that works. Any help will be appreciated

Thanks


Solution

  • Your problem is that you're not writing again the old sheets that the book contains. Let's say that you need to write it from scratch again, but no to execute to_excel again but just specify the workbook.

    This happens beacause xlsxwriter creates a new file, so the old one is erased.

    You can do it by using writer.book and writer.sheets objects.

    excelBook = load_workbook(filename)
    with pd.ExcelWriter(filename, engine='xlsxwriter') as writer:
        # Save your file workbook as base
        writer.book = excelBook
        writer.sheets = dict((ws.title, ws) for ws in excelBook.worksheets)
    
        # Now here add your new sheets
        result.to_excel(writer,'saw', index = False)
    
        # Save the file
        writer.save()
    

    Note: please notice that I've used load_workbook from openpyxl, but you can use Excelfile without it and reproduce it with just minor changes.