-1

I have a template file in Excel format. This template contains a title, subtitle and 2 headers that are located in A5:B5. How can I append my pandas DataFrame df to this template without deleting titles and headers? In particular, I want pandas DataFrame to be inserted starting from A6:B6, and then I want to save the result as a new file result.xlsx.

This is what I have so far.

import pandas as pd
from openpyxl import load_workbook

df = pd.DataFrame({'a':[1,3,5,7,4,5,6,4,7,8,9],
                   'b':[3,5,6,2,4,6,7,8,7,8,9]})

book = load_workbook("C:/template.xlsx")

writer = pd.ExcelWriter('template.xlsx')
df.to_excel(writer,'Sheet1',index=False)
writer.save() 
Fluxy
  • 2,838
  • 6
  • 34
  • 63
  • 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 Nov 29 '19 at 15:42

1 Answers1

1

There are startrow and startcol:

df.to_excel(writer, 'Sheet1', startrow=6, startcol=2)
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
  • Thanks. Why `startcol` is equal to 2, if it's A6:B6? Just to understand... – Fluxy Nov 29 '19 at 14:38
  • I never tried them, just know that they exist. I'm just putting random number there. `6` and `2` come from `B6`. TBH, i'm not sure what you meant by *starting at A6:B6*, that look two cells to me. – Quang Hoang Nov 29 '19 at 14:39
  • Ok, thanks. I tested it. Though DataFrame only takes 100Kb, this code line takes forever… Not sure why it happens. – Fluxy Nov 29 '19 at 14:50