How to Export Pandas DataFrame to Excel

Cody Schneider7 min read

Getting your hard-earned analysis out of a Pandas DataFrame and into an Excel file is a routine task for anyone working with data in Python. Whether you need to share results with colleagues, present data to a client, or simply prefer a spreadsheet for final tweaks, a clean export is essential. This guide covers how to export your DataFrame to Excel, starting with a one-line command and moving all the way to advanced techniques like writing to multiple sheets and adding custom formatting.

What You'll Need

Before you get started, make sure you have the Pandas library installed. You will also need an "engine" library for writing to Excel files. The two most popular ones are openpyxl (for .xlsx files) and xlsxwriter (for more advanced formatting). For most use cases, openpyxl is all you need.

You can install them using pip:

pip install pandas openpyxl xlsxwriter

The Basics: A Simple DataFrame to Excel Export

The core of exporting data from Pandas to Excel is the .to_excel() method. At its simplest, this function takes just one argument: the desired file path for your new Excel file.

Let's start with a sample DataFrame. Imagine you have some marketing campaign data.

import pandas as pd

# Creating a sample DataFrame
data = {
    'Campaign': ['Summer Sale', 'Back to School', 'Holiday Promo', 'Spring Fling'],
    'Spend': [5000, 7500, 15000, 6000],
    'PPC Clicks': [1200, 1800, 3500, 1500],
    'Conversions': [50, 95, 250, 75]
}

df = pd.DataFrame(data)

Now, to export this DataFrame to an Excel file named campaign_report.xlsx, you only need one line of code:

# The most basic export
df.to_excel('campaign_report.xlsx')

If you open this new file, you'll see your data neatly laid out in a sheet. You'll also notice something important: an extra, unnamed column at the beginning containing the numbers 0, 1, 2, and 3. This is the DataFrame's index. While useful inside Pandas, you rarely want it in your final report.

Customizing Your Export with Common Parameters

The .to_excel() function is incredibly powerful and offers several parameters to control exactly how your file looks. Let's cover the ones you'll use most often.

1. Removing the Index

This is the most common adjustment you'll make. To prevent Pandas from writing the index to your Excel file, simply set the index parameter to False.

df.to_excel('campaign_report_no_index.xlsx', index=False)

Now your output will look much cleaner, with only the data columns you intended to export.

2. Specifying a Sheet Name

By default, Pandas names the sheet "Sheet1". You can easily give it a more descriptive name with the sheet_name parameter.

df.to_excel('campaign_report.xlsx', index=False, sheet_name='Q4 Campaigns')

This is particularly useful for organizing your work and helps anyone opening the file understand the context of the data immediately.

3. Handling Missing Data

Sometimes your DataFrame will contain missing values, represented as NaN (Not a Number) in Pandas. In an Excel sheet, these empty cells might be confusing. You can use the na_rep parameter to specify a placeholder string for them.

Let's add a missing value to our DataFrame:

import numpy as np

df.loc[2, 'PPC Clicks'] = np.nan  # Add a missing value for demonstration

# Export with a custom placeholder for `NaN`
df.to_excel(
    'campaign_report_missing_data.xlsx',
    index=False,
    sheet_name='Q4 Campaigns',
    na_rep='N/A'
)

Now, instead of a blank cell, the report will show "N/A", making it clear that the data is intentionally missing.

4. Exporting Only Specific Columns

If you don't need to export your entire DataFrame, you can provide a list of column names to the columns parameter. This is a handy way to create summary reports without first creating a separate, smaller DataFrame in your script.

# Export only the campaign names and their conversion numbers
df.to_excel(
    'campaign_performance_summary.xlsx',
    index=False,
    sheet_name='Performance Summary',
    columns=['Campaign', 'Conversions']
)

This creates a focused view of your data, perfect for high-level summaries.

Advanced Exporting: Writing Multiple DataFrames to One Excel File

A common business need is to combine several related reports into a single Excel file, with each report on a separate sheet. Exporting two DataFrames to two different files is easy, but putting them in one file requires a slightly different approach using the pd.ExcelWriter object.

Let's create a second DataFrame with sales data to go along with our campaign data.

# Create a second DataFrame for sales data
sales_data = {
    'Product': ['Standard Widget', 'Premium Widget', 'Basic Widget'],
    'Month': ['Dec', 'Dec', 'Dec'],
    'Revenue': [150000, 250000, 75000]
}
df_sales = pd.DataFrame(sales_data)

# Use pd.ExcelWriter to export both DataFrames to the same file
with pd.ExcelWriter('multi_sheet_report.xlsx') as writer:
    df.to_excel(writer, sheet_name='Campaign Data', index=False)
    df_sales.to_excel(writer, sheet_name='Sales Revenue', index=False)

Here's what this code does:

  • pd.ExcelWriter('multi_sheet_report.xlsx') as writer: This creates an ExcelWriter object, which essentially opens up your Excel file and prepares it to be written to. Using it within a with statement is best practice because it ensures the file is properly saved and closed when you're done, even if errors occur.
  • df.to_excel(writer, ...): Instead of passing a file path to .to_excel(), you pass the writer object. This tells Pandas to write to the file being managed by the writer, rather than creating a new file.

This method lets you add as many sheets as you need, giving you a clean and organized way to package related datasets together.

Bonus: Adding Formatting for Polished Reports

While Pandas can't do complex formatting on its own, it integrates beautifully with the XlsxWriter library to give you total control over how your final Excel file looks. This lets you do things like adjust column widths, make headers bold, or add numeric formatting - all from your Python script.

First, specify XlsxWriter as the engine when creating your writer object. Then, you can access the workbook and worksheet objects to apply formats.

# Specify 'xlsxwriter' as the engine
with pd.ExcelWriter('formatted_report.xlsx', engine='xlsxwriter') as writer:
    df.to_excel(writer, sheet_name='Styled Campaign Data', index=False)

    # Get the workbook and worksheet objects
    workbook  = writer.book
    worksheet = writer.sheets['Styled Campaign Data']

    # --- Add formatting ---

    # 1. Define a bold format for headers
    header_format = workbook.add_format({
        'bold': True,
        'bg_color': '#DDEBF7'
    })

    # 2. Write the column headers with the defined format
    for col_num, value in enumerate(df.columns.values):
        worksheet.write(0, col_num, value, header_format)

    # 3. Set custom column widths for better readability
    worksheet.set_column('A:A', 20)  # Column A width
    worksheet.set_column('B:D', 15)  # Columns B to D width

With just a few extra lines, your automated report now looks like a human carefully prepared it. This is a game-changer for producing professional, ready-to-share documents without any manual intervention.

Excel vs. CSV: When to Use Which?

Pandas can just as easily export data to a CSV file using df.to_csv(). So when should you choose one over the other?

Use Excel (.xlsx) when:

  • You are sharing the file with stakeholders who are most comfortable working in Excel.
  • You need to include multiple tables in a single file (using different sheets).
  • You need to preserve data types like numbers and dates more reliably.
  • You want to apply basic cell formatting (like bold headers or column widths) directly from your script.

Use CSV (.csv) when:

  • The output is intended for another application or database, as CSV is a more universal format.
  • File size is a concern, as CSVs are simple text files and generally smaller than Excel files.
  • You need a simple, human-readable file that can be opened in any text editor.
  • You don't need any formatting, charts, or multiple sheets.

Final Thoughts

Mastering the to_excel() function elevates your ability to move data out of your analysis environment and into a format ready for collaboration and business reporting. From a simple one-liner to creating polished multi-sheet workbooks, these methods are staples for any analyst using Python.

While writing Python scripts to export data is enormously powerful, it's often just one part of a time-consuming reporting cycle that involves connecting data, running code, and sharing static files. At Graphed, we’ve focused on simplifying this entire workflow. We allow you to connect all your data sources just once and then use natural language to build and interact with real-time dashboards. It moves you from manually pulling and pushing files to having a live, shareable view of your business performance, so you can spend less time updating reports and more time acting on the insights.

Related Articles

How to Connect Facebook to Google Data Studio: The Complete Guide for 2026

Connecting Facebook Ads to Google Data Studio (now called Looker Studio) has become essential for digital marketers who want to create comprehensive, visually appealing reports that go beyond the basic analytics provided by Facebook's native Ads Manager. If you're struggling with fragmented reporting across multiple platforms or spending too much time manually exporting data, this guide will show you exactly how to streamline your Facebook advertising analytics.

Appsflyer vs Mixpanel​: Complete 2026 Comparison Guide

The difference between AppsFlyer and Mixpanel isn't just about features—it's about understanding two fundamentally different approaches to data that can make or break your growth strategy. One tracks how users find you, the other reveals what they do once they arrive. Most companies need insights from both worlds, but knowing where to start can save you months of implementation headaches and thousands in wasted budget.