Pandas docs says it uses openpyxl for xlsx files. Quick look through the code in ExcelWriter gives a clue that something like this might work out:

import pandas
from openpyxl import load_workbook

book = load_workbook('Masterfile.xlsx')
writer = pandas.ExcelWriter('Masterfile.xlsx', engine='openpyxl') 
writer.book = book

## ExcelWriter for some reason uses writer.sheets to access the sheet.
## If you leave it empty it will not know that sheet Main is already there
## and will create a new sheet.

writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])

writer.save()
Answer from Ski on Stack Overflow
Top answer
1 of 16
191

Pandas docs says it uses openpyxl for xlsx files. Quick look through the code in ExcelWriter gives a clue that something like this might work out:

import pandas
from openpyxl import load_workbook

book = load_workbook('Masterfile.xlsx')
writer = pandas.ExcelWriter('Masterfile.xlsx', engine='openpyxl') 
writer.book = book

## ExcelWriter for some reason uses writer.sheets to access the sheet.
## If you leave it empty it will not know that sheet Main is already there
## and will create a new sheet.

writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])

writer.save()
2 of 16
64

UPDATE: Starting from Pandas 1.3.0 the following function will not work properly, because functions DataFrame.to_excel() and pd.ExcelWriter() have been changed - a new if_sheet_exists parameter has been introduced, which has invalidated the function below.

Here you can find an updated version of the append_df_to_excel(), which is working for Pandas 1.3.0+.


Here is a helper function:

import os
from openpyxl import load_workbook


def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
                       truncate_sheet=False, 
                       **to_excel_kwargs):
    """
    Append a DataFrame [df] to existing Excel file [filename]
    into [sheet_name] Sheet.
    If [filename] doesn't exist, then this function will create it.

    @param filename: File path or existing ExcelWriter
                     (Example: '/path/to/file.xlsx')
    @param df: DataFrame to save to workbook
    @param sheet_name: Name of sheet which will contain DataFrame.
                       (default: 'Sheet1')
    @param startrow: upper left cell row to dump data frame.
                     Per default (startrow=None) calculate the last row
                     in the existing DF and write to the next row...
    @param truncate_sheet: truncate (remove and recreate) [sheet_name]
                           before writing DataFrame to Excel file
    @param to_excel_kwargs: arguments which will be passed to `DataFrame.to_excel()`
                            [can be a dictionary]
    @return: None

    Usage examples:

    >>> append_df_to_excel('d:/temp/test.xlsx', df)

    >>> append_df_to_excel('d:/temp/test.xlsx', df, header=None, index=False)

    >>> append_df_to_excel('d:/temp/test.xlsx', df, sheet_name='Sheet2',
                           index=False)

    >>> append_df_to_excel('d:/temp/test.xlsx', df, sheet_name='Sheet2', 
                           index=False, startrow=25)

    (c) MaxU
    """
    # Excel file doesn't exist - saving and exiting
    if not os.path.isfile(filename):
        df.to_excel(
            filename,
            sheet_name=sheet_name, 
            startrow=startrow if startrow is not None else 0, 
            **to_excel_kwargs)
        return
    
    # ignore [engine] parameter if it was passed
    if 'engine' in to_excel_kwargs:
        to_excel_kwargs.pop('engine')

    writer = pd.ExcelWriter(filename, engine='openpyxl', mode='a')

    # try to open an existing workbook
    writer.book = load_workbook(filename)
    
    # get the last row in the existing Excel sheet
    # if it was not specified explicitly
    if startrow is None and sheet_name in writer.book.sheetnames:
        startrow = writer.book[sheet_name].max_row

    # truncate sheet
    if truncate_sheet and sheet_name in writer.book.sheetnames:
        # index of [sheet_name] sheet
        idx = writer.book.sheetnames.index(sheet_name)
        # remove [sheet_name]
        writer.book.remove(writer.book.worksheets[idx])
        # create an empty sheet [sheet_name] using old index
        writer.book.create_sheet(sheet_name, idx)
    
    # copy existing sheets
    writer.sheets = {ws.title:ws for ws in writer.book.worksheets}

    if startrow is None:
        startrow = 0

    # write out the new sheet
    df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)

    # save the workbook
    writer.save()

Tested with the following versions:

  • Pandas 1.2.3
  • Openpyxl 3.0.5
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.to_excel.html
pandas.DataFrame.to_excel — pandas 3.0.5 documentation
df2.to_excel(writer, sheet_name="Sheet_name_2") ExcelWriter can also be used to append to an existing Excel file:
Discussions

How to write XLSX Excel file row by row?
Hi I’m new to Python. I have not yet finished a 70 hour tutorial. My home system: Python 3.12 on MS Windows 11 Home. I’m looking to learn how to write an Excel XLSX file using Pandas, or perhaps another writer but I have special requirements. What I’ve researched and my notes. More on discuss.python.org
🌐 discuss.python.org
4
0
February 25, 2024
python - Pandas Excel writer update existing excel file - Data Science Stack Exchange
How do I update an excel file and not overwrite it? #Run function query_data(atlantic_stones) query_data(aircool_north) query_data(aircool_south) #Create some Pandas dataframes dfastones = quer... More on datascience.stackexchange.com
🌐 datascience.stackexchange.com
Overwrite existing Excel data using Pandas
I think your writer object that you create is messed up. In the first part you are initializing the writer without saving. Try using context manager in that scenario. that way you will avoid a situation like this, i.e. not closing/saving. the same applies for opening files etc. More on reddit.com
🌐 r/learnpython
26
2
July 2, 2022
I can't figure out how to use .append_df_to_excel() function
I've never heard of a pandas dataframe method named that. From the pandas docs here's a code snippet on how to add a new sheet to an existing xls file: with pd.ExcelWriter('output.xlsx',mode='a') as writer: df.to_excel(writer, sheet_name='Sheet_name_3') More on reddit.com
🌐 r/learnpython
6
0
December 13, 2022
🌐
Reddit
reddit.com › r/learnpython › overwrite existing excel data using pandas
r/learnpython on Reddit: Overwrite existing Excel data using Pandas
July 2, 2022 -

I have a 'test' document where I'm learning to overwrite an existing Excel document with data. I find that each time I run the program the old data is removed and replaced with new data, but I want to preserve that old data in this case.

I'm going to run about a dozen different queries from oracle, then write them to a specific column in the document. Each query will end up being its own function (maybe the wrong approach?)

In this code, I tried to replicate the functionality without using the DB but I find when I run in that only func_2 data remains in the spreadsheet. How can I fix that?

import pandas as pd

def func_1():
    data = {
        'CHN': {'COUNTRY': 'China', 'POP': 1_398.72, 'AREA': 9_596.96,
                'GDP': 12_234.78, 'CONT': 'Asia'},
        'IND': {'COUNTRY': 'India', 'POP': 1_351.16, 'AREA': 3_287.26,
                'GDP': 2_575.67, 'CONT': 'Asia', 'IND_DAY': '1947-08-15'},
        'USA': {'COUNTRY': 'US', 'POP': 329.74, 'AREA': 9_833.52,
                'GDP': 19_485.39, 'CONT': 'N.America',
                'IND_DAY': '1776-07-04'},
        'IDN': {'COUNTRY': 'Indonesia', 'POP': 268.07, 'AREA': 1_910.93,
                'GDP': 1_015.54, 'CONT': 'Asia', 'IND_DAY': '1945-08-17'},
        'BRA': {'COUNTRY': 'Brazil', 'POP': 210.32, 'AREA': 8_515.77,
                'GDP': 2_055.51, 'CONT': 'S.America', 'IND_DAY': '1822-09-07'}
    }

    df = pd.DataFrame(data)
    writer = pd.ExcelWriter(
        'C:\\Users\\Newbook.xlsx')
    df.to_excel(writer, sheet_name="rawSource", startcol=1, startrow=5)
    func_2(data)

def func_2(data):
    df = pd.DataFrame(data)
    writer = pd.ExcelWriter(
        'C:\\Users\\Newbook.xlsx')
    df.to_excel(writer, sheet_name="rawSource", startcol=2, startrow=10)
    writer.save()

if __name__ == '__main__':
    func_1()

While typing this up I had the thought... of passing the writer variable from func_1 to func_2, which appears to solve the problem but I decided to post this anyway in case there is any other useful feedback.

Updated Solution:

I found that if the sheet I'm opening has existing tabs that my code is deleting all that each time... so I found that I could use openpyxl to load the workbook first then pass it to the ExcelWriter in pandas to update it.

It appears writer.sheets is necessary so it can find the sheet you want, otherwise it will create one.

def func_1():
    data = {
        'CHN': {'COUNTRY': 'China', 'POP': 1_398.72, 'AREA': 9_596.96,
                'GDP': 12_234.78, 'CONT': 'Asia'},
        'IND': {'COUNTRY': 'India', 'POP': 1_351.16, 'AREA': 3_287.26,
                'GDP': 2_575.67, 'CONT': 'Asia', 'IND_DAY': '1947-08-15'},
        'USA': {'COUNTRY': 'US', 'POP': 329.74, 'AREA': 9_833.52,
                'GDP': 19_485.39, 'CONT': 'N.America',
                'IND_DAY': '1776-07-04'},
        'IDN': {'COUNTRY': 'Indonesia', 'POP': 268.07, 'AREA': 1_910.93,
                'GDP': 1_015.54, 'CONT': 'Asia', 'IND_DAY': '1945-08-17'},
        'BRA': {'COUNTRY': 'Brazil', 'POP': 210.32, 'AREA': 8_515.77,
                'GDP': 2_055.51, 'CONT': 'S.America', 'IND_DAY': '1822-09-07'}
    }

    book = load_workbook(
        'C:\\Users\\Newbook.xlsx')

    with pd.ExcelWriter(
            'C:\\Users\\Newbook.xlsx', engine='openpyxl') as writer:
        writer.book = book
        writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

        df.to_excel(writer, index=False, header=False,
                    sheet_name="Sheet1", startcol=0, startrow=2)
        func_2(writer)
🌐
Edureka Community
edureka.co › home › community › categories › others › how can we write new data to existing excel...
How can we write new data to existing Excel spreadsheet | Edureka Community
October 14, 2022 - I have a weekly procedure that generates a data frame with about 1,000 entries. In order to avoid ... ) df.to_excel(writer, index=False) writer.save()
🌐
Medium
medium.com › @amit25173 › working-with-pandas-excelwriter-75f549376793
Working with pandas.ExcelWriter. I understand that learning data science… | by Amit Yadav | Medium
March 6, 2025 - Here’s something that might surprise you: writing to an existing Excel file doesn’t automatically append data — it often overwrites it. But don’t worry, there’s a way around this. ... from openpyxl import load_workbook import pandas as pd # Load existing workbook book = load_workbook('output.xlsx') writer = pd.ExcelWriter('output.xlsx', engine='openpyxl') writer.book = book # Append new data new_data = pd.DataFrame({'Name': ['David'], 'Age': [40]}) new_data.to_excel(writer, sheet_name='Sheet1', index=False, startrow=writer.sheets['Sheet1'].max_row, header=False) writer.save()
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.ExcelWriter.html
pandas.ExcelWriter — pandas 3.0.5 documentation
class pandas.ExcelWriter(path, engine=None, date_format=None, datetime_format=None, mode='w', storage_options=None, if_sheet_exists=None, engine_kwargs=None)[source]# Class for writing DataFrame objects into excel sheets. ... See DataFrame.to_excel() for typical usage. The writer should be used as a context manager. Otherwise, call close() to save and close any opened file handles.
🌐
Python.org
discuss.python.org › python help
How to write XLSX Excel file row by row? - Python Help - Discussions on Python.org
February 25, 2024 - Hi I’m new to Python. I have not yet finished a 70 hour tutorial. My home system: Python 3.12 on MS Windows 11 Home. I’m looking to learn how to write an Excel XLSX file using Pandas, or perhaps another writer but I ha…
Find elsewhere
🌐
Stack Exchange
datascience.stackexchange.com › questions › 46719 › pandas-excel-writer-update-existing-excel-file
python - Pandas Excel writer update existing excel file - Data Science Stack Exchange
writer = pd.ExcelWriter('data_repository.xlsx', engine='xlsxwriter') dfastones.to_excel(writer, sheet_name='atlantic_stones') dfanorth.to_excel(writer, sheet_name='aircool_north') dfasouth.to_excel(writer, sheet_name='aircool_south') #Close the Pandas Excel writer and output the Excel file.
🌐
YouTube
youtube.com › automate with rakesh
Pandas Write to Excel without Deleting Other Sheets - YouTube
Learn how to write data to an Excel file using Pandas without overwriting or deleting other sheets. In this tutorial, we'll guide you through the process of ...
Published   September 27, 2023
Views   1K
🌐
CopyProgramming
copyprogramming.com › howto › append-existing-excel-sheet-with-new-dataframe-using-python-pandas
Python: Adding a New Dataframe to an Existing Excel Sheet using Python Pandas
June 4, 2023 - Python - append dataframe to excel ... using python pandas. you might also consider header=False . so it should look like: df1.to_excel (writer, startrow = 2,index = False, Header = False) ... docstring in pandas dev github excelwriter will support parameter add worksheet to ...
🌐
XlsxWriter
xlsxwriter.readthedocs.io › example_pandas_positioning.html
Example: Pandas Excel dataframe positioning — XlsxWriter
# # SPDX-License-Identifier: ... pd.DataFrame({"Data": [31, 32, 33, 34]}) df4 = pd.DataFrame({"Data": [41, 42, 43, 44]}) # Create a Pandas Excel writer using XlsxWriter as the engine. writer = pd.ExcelWriter("pandas_positioning.xlsx", engine="xlsxwriter") # Position the dataframes ...
🌐
XlsxWriter
xlsxwriter.readthedocs.io › example_pandas_multiple.html
Example: Pandas Excel with multiple dataframes — XlsxWriter
# # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2013-2025, John McNamara, jmcnamara@cpan.org # import pandas as pd # Create some Pandas dataframes from some data. df1 = pd.DataFrame({"Data": [11, 12, 13, 14]}) df2 = pd.DataFrame({"Data": [21, 22, 23, 24]}) df3 = pd.DataFrame({"Data": [31, 32, 33, 34]}) # Create a Pandas Excel writer using XlsxWriter as the engine. writer = pd.ExcelWriter("pandas_multiple.xlsx", engine="xlsxwriter") # Write each dataframe to a different worksheet. df1.to_excel(writer, sheet_name="Sheet1") df2.to_excel(writer, sheet_name="Sheet2") df3.to_excel(writer, sheet_name="Sheet3") # Close the Pandas Excel writer and output the Excel file.
🌐
Kfjt2022
yvg.kfjt2022.de › pages › how-to-append-data-in-excel-using-python-pandas.html
how to append data in excel using python pandas
In order to accomplish this goal, you&x27;ll need to use readexcel. File mode to use (write or append). import pandas as pd df pd. python' import all of the data from a folder of excel files. toexcel (writer, &x27;Existingsheetname&x27;) writer. This short article shows how you can read in all the tabs in an Excel workbook and combine them into a single pandas dataframe using one command.
🌐
Finxter
blog.finxter.com › home › learn python blog › how to read and write excel files with pandas
How to Read and Write Excel files with Pandas - Be on the Right Side of Change
October 17, 2021 - Inside the to_excel() function we respectively put in the variable “writer” as the path. We also use the “sheet_name” parameter and the respective name of the sheet and set the “index” parameter to “False” to get rid of the extra ...
🌐
Py4u
py4u.net › discuss › 10371
Page not found
Page not found The page you're looking for is not found, please go to the main page · Popular Tutorials · Python Data Types · Comparison Operators · Lists In Python · Variable Assignments · Strings In Python · This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 ...
🌐
NewbeDEV
newbedev.com › how-to-save-a-new-sheet-in-an-existing-excel-file-using-pandas
How to save a new sheet in an existing excel file, using Pandas?
Essentially these steps are just loading the existing data from 'Masterfile.xlsx' and populating your writer with them. Now let's say you already have a file with x1 and x2 as sheets. You can use the example code to load the file and then could do something like this to add x3 and x4. path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx" writer = pd.ExcelWriter(path, engine='openpyxl') df3.to_excel(writer, 'x3', index=False) df4.to_excel(writer, 'x4', index=False) writer.save()
🌐
Semicolonworld
semicolonworld.com › question › 43123 › how-to-write-to-an-existing-excel-file-without-overwriting-data-using-pandas
Redirecting...
Learn Web Development,PHP,MySQL,javaScript,jQuery,Ajax,Wordpress,Drupal,Codelgniter,CakePHP With SemicolonWorld Tutorial. View Live Demo And Download Source Code.
🌐
Codegrepper
codegrepper.com › code-examples › python › write+pandas+dataframe+to+existing+excel+sheet
write pandas dataframe to existing excel sheet Code Example
#Python, pandas #To export a pandas dataframe into Excel df.to_excel(r'Path where you want to store the exported excel file\File Name.xlsx', index = False)