python writing a df to a specific cell of excel

Question:

I have come across a lot of answers and just wanted to check if this is the best answer
Write pandas dataframe values to excel to specific cell in a specific sheet.

The question is – assuming I have a dataframe "df".
I want to write to an existing excel file called "Name1.xlsx", in
worksheet called "exampleNames", and starting at cell d25.

What’s the easiest/ most efficient way to do that.

###############Updated!#############

I tried this

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import openpyxl


path = "C:\Users\ABC\PycharmProjects\ABC\Name1.xlsx"

df = pd.DataFrame(np.random.randint(1,10,(3,2)),columns=['a','b'])

df.to_excel(path,sheet_name="exampleNames",startcol=5,startrow=5,header=None,index=False)
df.to_excel(path,sheet_name="NN",startcol=5,startrow=25,header=None,index=False)

gave me error
ModuleNotFoundError: No module named ‘openpyxl’

Asked By: TRex

||

Answers:

This is the approach suggested in the pandas docs

df.to_excel(writer, sheet_name='Sheet1', startcol=col,startrow=row, header=None)

where writer could be path-like, file-like, or ExcelWriter object

eg

df.to_excel('sample.xlsx',sheet_name="exampleNames",startcol=5,startrow=5,header=None)

To save multiple dataframes in excel, you will have to use the writer object

with pd.ExcelWriter('output.xlsx', engine="openpyxl", mode='a', if_sheet_exists='overlay') as writer:
    df1.to_excel(writer, sheet_name='exampleNames' ,startcol=5,startrow=5,header=None,index=False)
    df2.to_excel(writer, sheet_name='NN', startcol=5,startrow=25,header=None,index=False)
Answered By: Himanshu Poddar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.