Python Forum

Full Version: How to add a dataframe to an existing excel file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I am trying to add a dataframe to an existing sheet. I don't see any error, but the data does not show on the sheet.

Is anyone able to tell me what am I missing?

Thank you!

#Grab dataframe from another excel sheet
df = pd.read_excel('C:/path/Dataframe_File.xlsx',sheetname='Data') 

#Open existing excel file
workbook1 = openpyxl.load_workbook('C:/path/Existing_File.xlsx')

writer = pd.ExcelWriter('C:/path/Existing_File.xlsx', engine='openpyxl') 

#Add dataframe to excel file 
df.to_excel(writer,sheet_name="Sheet",index=False,startrow=17,startcol=1,engine='openpyxl')

workbook1.save('C:/path/Existing_File.xlsx')
It's just a guess but maybe you need administrator priviledges to write on that path (e.g. I have to run command prompt as administrator to use "pip install" just because it's on C drive, maybe that is also the case with saving your file)
I found a way around like this.

from openpyxl import load_workbook
workbook1 = openpyxl.load_workbook('file.xlsx')

writer = pd.ExcelWriter('file.xlsx', engine='openpyxl') 
writer.book = workbook1
new_file.to_excel(writer, sheet_name='Shee1',index=False,startrow=2,startcol=1)

writer.save()
writer.close()