1

I have a workbook called "Pivot Template.xlsx". I have data from a query in a Pandas dataframe called "results". I need to put this data on a tab called "Pivot Data". I am using the code below for writing to the file, but the problem is that deletes all of the existing tabs when writing the file.

writer = pandas.ExcelWriter('Pivot Template.xlsx', engine='xlsxwriter')
results.to_excel(writer, sheet_name='Pivot Data', index=False, encoding='utf8')
writer.save()

I would like to get this working with just Pandas or openpyxl. As one other catch, I have several other tabs that have pivot tables based off of this tab and I would like them to work after doing this write.

Eric Shreve
  • 176
  • 1
  • 3
  • 10
  • Possible duplicate of [How to write to an existing excel file without overwriting data (using pandas)?](https://stackoverflow.com/questions/20219254/how-to-write-to-an-existing-excel-file-without-overwriting-data-using-pandas) – Charlie Clark Dec 28 '17 at 16:29
  • I checked the possible duplicate question and it answered the question in that it does show how to write to an existing tab. However, It destroys the pivot tables on the other pages. I need this to be able to keep the pivot tables in tact. – Eric Shreve Dec 28 '17 at 16:44
  • 1
    You need openpyxl version 2.5 – Charlie Clark Dec 28 '17 at 17:47
  • OK. I updated to 2.5 and now it works. Thanks @CharlieClark! Below is the code I used to get this to work: ` book = openpyxl.load_workbook('Pivot Template.xlsx') writer = pandas.ExcelWriter('Pivot Template.xlsx', engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) results.to_excel(writer, 'Pivot Data', index=False) writer.save() ` – Eric Shreve Dec 28 '17 at 18:13

0 Answers0