[Python] How to Export Pandas DataFrame to Excel File (to_excel)

When sharing data analysis results as reports, formatted Excel files (.xlsx) are often required instead of CSVs. By using the Pandas to_excel method, you can save the contents of a DataFrame as an Excel file.

This article explains the basic export method, as well as key parameters for adjusting output positions and writing to multiple sheets. Note that the openpyxl library must be installed in advance to perform Excel export (pip install openpyxl).

目次

Key Parameters of to_excel

The to_excel method provides numerous options to finely control the output format. The frequently used parameters are as follows:

ParameterMeaning / Role
sheet_nameSpecifies the destination sheet name (Default is ‘Sheet1’).
indexSpecifies whether to export the DataFrame index (row labels). Setting this to False removes row numbers.
columnsLimits the columns to export or specifies their order. Specified as a list.
startrowSpecifies the row position to start writing (0-based). Used when you want to create empty rows at the top.
startcolSpecifies the column position to start writing (0-based). Used when you want to create empty columns on the left.

Implementation Sample Code

Below is the code for Excel export in three different scenarios: basic export, specifying output position/columns, and writing to multiple sheets.

import pandas as pd
import os

def export_to_excel_demo():
    """
    Function to demonstrate various patterns of Excel file export using Pandas
    """
    
    # Create sample data: Employee performance data
    employee_data = {
        "Employee_ID": [101, 102, 103, 104],
        "Name": ["K. Tanaka", "M. Sato", "S. Suzuki", "Y. Honda"],
        "Department": ["Sales", "Engineering", "Sales", "HR"],
        "Score": [85, 92, 78, 88],
        "Join_Date": ["2023-04-01", "2022-10-01", "2024-01-01", "2023-06-01"]
    }
    df = pd.DataFrame(employee_data)

    output_file_basic = "employee_report_basic.xlsx"
    output_file_multi = "employee_report_multi.xlsx"


    # ---------------------------------------------------------
    # 1. Basic Export and Parameter Specification
    # ---------------------------------------------------------
    print(f"=== 1. Basic Excel Export: {output_file_basic} ===")
    
    # index=False: Do not export row numbers (commonly used setting)
    # sheet_name: Specify sheet name as "Performance_2025"
    df.to_excel(
        output_file_basic, 
        index=False, 
        sheet_name="Performance_2025"
    )
    print("Save complete.\n")


    # ---------------------------------------------------------
    # 2. Adjusting Output Position (startrow, startcol) and Limiting Columns (columns)
    # ---------------------------------------------------------
    print("=== 2. Position Adjustment and Column Specification ===")
    
    # Export only specific columns using the columns argument (Name and Score only)
    # startrow=2: Start writing from the 3rd row from the top (Index 2)
    # startcol=1: Start writing from the 2nd column from the left (Column B, Index 1)
    # * This reserves space in Column A or rows 1-2 for adding titles later
    
    output_file_custom = "employee_report_custom.xlsx"
    
    df.to_excel(
        output_file_custom,
        index=False,
        columns=["Name", "Score"],
        startrow=2,
        startcol=1,
        sheet_name="Summary"
    )
    print(f"Custom export complete: {output_file_custom}\n")


    # ---------------------------------------------------------
    # 3. Exporting Multiple DataFrames to Separate Sheets (ExcelWriter)
    # ---------------------------------------------------------
    print(f"=== 3. Writing to Multiple Sheets: {output_file_multi} ===")
    
    # Split data by department
    df_sales = df[df["Department"] == "Sales"]
    df_eng = df[df["Department"] == "Engineering"]

    # Use pd.ExcelWriter when creating multiple sheets in a single Excel file
    # mode="w" means create new (overwrite)
    with pd.ExcelWriter(output_file_multi, engine="openpyxl") as writer:
        
        # Sheet 1: Sales Department
        df_sales.to_excel(writer, sheet_name="Sales_Dept", index=False)
        
        # Sheet 2: Engineering Department
        df_eng.to_excel(writer, sheet_name="Engineering_Dept", index=False)

    print("Multiple sheet save complete.")

    # (Reference) File deletion process
    # os.remove(output_file_basic)
    # os.remove(output_file_custom)
    # os.remove(output_file_multi)

if __name__ == "__main__":
    export_to_excel_demo()

Explanation of the Code

Using Basic Parameters

df.to_excel("filename.xlsx", index=False) is the most standard syntax. While Pandas DataFrames have a row number (index) starting from 0 by default, this row number is often unnecessary when creating Excel files for business reports, so index=False is specified.

Adjusting Position (startrow, startcol)

startrow and startcol are useful when you want to start writing data from a location other than the top-left (cell A1). For example, if there is a fixed company format and you want to manually enter “Creation Date” or “Department Name” in the header section, you can accommodate this by shifting the starting position of the data part.

Writing to Multiple Sheets (ExcelWriter)

If you simply run to_excel twice for the same file, the second execution will overwrite the file itself, and the contents of the first execution will be lost.

If you want to write data to different sheets in the same file, you need to create a pd.ExcelWriter object and pass it as the first argument (writer) to to_excel. This allows you to manage multiple sheets within a single Excel workbook.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次