0

I need to write multiple dataframes to an excel file. These dataframes needs to be written to a specific sheet and it should not overwrite existing data on that sheet.

The code I have is as follows:

excelbook = test.xlsx
book = load_workbook(excelbook)
writer = pd.ExcelWriter(excelbook, engine = 'openpyxl')
writer.book = book
df.to_excel(writer, sheet_name = 'apple', startcol=5, startrow=0)

writer.save()
writer.close()

Problem with my code is, each time I run it to write a dataframe, it is creating a new sheet in the excel file. For example, if the sheet name I need is "apple", then since I'm running this piece of code 3 times (to write 3 dataframes to the same sheet), it is creating a new sheet each time and naming them as - "apple1", "apple2" and "apple3"

I need to write multiple dataframes to the same excel file, to the same sheet in that file, without overwriting the existing data in the sheet.

Please help. Thanks in advance.

PKV
  • 167
  • 3
  • 13
  • "without overwriting the existing data in the sheet". What is the rule that tells you where on the sheet the new data should go? – Karl Knechtel Jul 08 '20 at 07:08
  • This should fix it for you; Please upvote the answer if it helps @ Mayank Porwal https://stackoverflow.com/questions/61933021/how-to-overwrite-data-on-an-existing-excel-sheet-while-preserving-all-other-shee – wwnde Jul 08 '20 at 07:13
  • Hi! So, I have this piece of code in 3 separate places in the program, and each time I'm giving specific row and col values using - startcol=xx, startrow=xx (these values change each time). – PKV Jul 08 '20 at 07:15
  • Is this what you are looking for? https://stackoverflow.com/questions/47737220/append-dataframe-to-excel-with-pandas/47738103 – Muntasir Wahed Jul 08 '20 at 07:15
  • Hello Mayank! I did try this solution. The issue with that is, out of the 3 times I'm writing to the excel file, the first time I'm creating a new sheet with the name 'apple'. For the remaining 2 dataframes, I used the code you mentioned, however it is writing the dataframes to the default sheet and not the one I created ('apple'). – PKV Jul 08 '20 at 07:23

0 Answers0