How to Save DataFrame to Excel in Python
Moving your data analysis from a Python script to a shareable Excel spreadsheet is a crucial last step for many projects. Instead of just exporting raw data, you need a clean, professional-looking report that your team or clients can easily understand. This tutorial will walk you through saving your pandas DataFrames to Excel, from the simplest one-sheet export to creating multi-sheet workbooks with custom formatting.
Getting Your Environment Ready
Before we start exporting, you need a couple of things in place. First, you'll need the pandas library, which is the foundation for data manipulation in Python. If you don't have it installed, open your terminal or command prompt and run this simple command:
pip install pandasNext, pandas needs an engine to actually write Excel files. Think of it like this: pandas knows what to write, but it needs a helper library to know how to write the .xlsx file. The two most popular engines are openpyxl and XlsxWriter. We'll install both, as they have different strengths that we'll explore.
pip install openpyxl xlsxwriterWith that, you're all set. Let's create a sample DataFrame that we can use for all the examples in this guide.
import pandas as pd
# Create a sample DataFrame
data = {
'OrderID': [101, 102, 103, 104, 105],
'Product': ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Webcam'],
'Region': ['East', 'West', 'East', 'North', 'West'],
'Quantity': [5, 12, 8, 3, 10],
'SalePrice': [1200.00, 25.50, 75.00, 300.75, 55.00]
}
df_sales = pd.DataFrame(data)
print(df_sales)The Simplest Method: Saving a DataFrame to a Single Excel Sheet
The most common task is saving a single DataFrame to an Excel file. Pandas makes this incredibly straightforward with the to_excel() method. Just call it on your DataFrame and provide a file name.
df_sales.to_excel('simple_sales_report.xlsx')If you open the newly created simple_sales_report.xlsx file, you'll see your data. However, you'll probably notice an extra, unnamed column at the beginning. This is the DataFrame's index. While the index is useful within pandas, it often just adds clutter to a final report.
Fortunately, turning it off is easy. Just add the index=False argument:
df_sales.to_excel('sales_report_no_index.xlsx', index=False)That looks much cleaner! You can also customize the name of the sheet inside the Excel file using the sheet_name argument. If you don't provide one, it defaults to 'Sheet1'.
df_sales.to_excel(
'sales_report_custom_sheet.xlsx',
index=False,
sheet_name='Q3 Sales Data'
)Writing Multiple DataFrames into One Excel File
What if you have several related DataFrames — say, sales, marketing costs, and inventory levels — and you want them all in one organized workbook, each on its own sheet? Exporting them one by one would create three separate files. Instead, you can use the pd.ExcelWriter object to manage a single file and direct each DataFrame to a specific sheet.
First, let's create two more sample DataFrames so we have something to work with:
# Marketing data
marketing_data = {
'Campaign': ['Google Ads', 'Facebook Ads', 'Email Campaign'],
'Spend': [2500, 1800, 950],
'Conversions': [50, 75, 120]
}
df_marketing = pd.DataFrame(marketing_data)
# Inventory data
inventory_data = {
'Product': ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Webcam'],
'InStock': [35, 150, 80, 22, 60]
}
df_inventory = pd.DataFrame(inventory_data)Now, we can use pd.ExcelWriter to put them all together. The recommended approach is to use a with statement, which automatically handles closing and saving the file once you're done.
with pd.ExcelWriter('comprehensive_report.xlsx') as writer:
df_sales.to_excel(writer, sheet_name='Sales', index=False)
df_marketing.to_excel(writer, sheet_name='MarketingSpend', index=False)
df_inventory.to_excel(writer, sheet_name='Inventory_Levels', index=False)Let's break down what's happening here:
with pd.ExcelWriter('comprehensive_report.xlsx') as writer:— creates an Excel writer object namedwriterthat points to our target file.df_sales.to_excel(writer, ...):— callsto_excel()on each DataFrame, passing thewriterobject instead of a filename.sheet_name='...'— assigns a unique sheet name for each DataFrame to keep them organized.
When the with block finishes, Python automatically saves the workbook with all three sheets. This method is the clean, standard way to create organized, multi-sheet reports.
Advanced Control: Formatting and Styling Your Excel Output
Exporting data is useful, but professional reports often require formatting to make them readable and highlight key information. This is where the XlsxWriter engine truly shines. We can access its features directly through our pandas ExcelWriter to apply number formats, change column widths, and style headers.
Here's how you can create the same multi-sheet report but add some useful formatting.
1. Adjusting Column Widths Automatically
One of the most common annoyances is that default Excel columns are often too narrow, cutting off text. We can programmatically set the width of each column to fit its content. In this example, we'll write a simple loop that finds the length of the longest item in each column (including the header) and sets the column width accordingly.
# Define the file path
output_filename = 'formatted_report.xlsx'
with pd.ExcelWriter(output_filename, engine='xlsxwriter') as writer:
# --- Write the Sales Sheet ---
df_sales.to_excel(writer, sheet_name='Sales', index=False)
# Get the xlsxwriter workbook and worksheet objects
workbook = writer.book
worksheet = writer.sheets['Sales']
# Iterate through each column and set the width
for i, col in enumerate(df_sales.columns):
# Find the maximum length of the string in the column
column_len = max(df_sales[col].astype(str).map(len).max(), len(col))
# Add a little extra small padding
worksheet.set_column(i, i, column_len + 2)
# --- Write the Other Sheets (for simplicity, we'll write them without formatting) ---
df_marketing.to_excel(writer, sheet_name='MarketingSpend', index=False)
df_inventory.to_excel(writer, sheet_name='Inventory_Levels', index=False)2. Adding Number Formats and Header Styles
Let's take it a step further. We want to format our SalePrice column as currency and make our header bold with a background color. To do this, we create "format objects" using the workbook and then apply them.
Since applying formats column-by-column requires a bit more manual control, we'll only format our Sales sheet here.
with pd.ExcelWriter('fully_styled_report.xlsx', engine='xlsxwriter') as writer:
# Send df_sales to Excel but don't write the header yet
df_sales.to_excel(writer, sheet_name='Sales', index=False, startrow=1, header=False)
# Get the workbook and worksheet objects
workbook = writer.book
worksheet = writer.sheets['Sales']
# --- Create Format Objects ---
# Header format
header_format = workbook.add_format({
'bold': True,
'valign': 'top',
'fg_color': '#D7E4BC',
'border': 1
})
# Currency format for the 'SalePrice' column
currency_format = workbook.add_format({'num_format': '$#,##0.00'})
# --- Write the header with formatting ---
for col_num, value in enumerate(df_sales.columns.values):
worksheet.write(0, col_num, value, header_format)
# --- Apply formats to columns ---
# Set currency format for the 'SalePrice' column (column E, index 4)
worksheet.set_column(4, 4, None, currency_format)
# Auto-fit column widths (re-using the logic from before)
for i, col in enumerate(df_sales.columns):
column_len = max(df_sales[col].astype(str).map(len).max(), len(col))
worksheet.set_column(i, i, column_len + 2)In this more advanced script, we explicitly wrote the header so we could apply our custom header_format. We then told pandas to write the DataFrame data starting from the second row (startrow=1) and applied our currency format to the entire 'SalePrice' column. This gives you fine-grained control to produce presentation-ready reports directly from Python.
More Tips and Common Operations
Here are a few more frequent scenarios and how to handle them.
Appending a Sheet to an Existing Excel File
Sometimes you need to add a new sheet to a workbook that already exists without overwriting it. You can do this by setting the mode to 'a' for append and specifying openpyxl as the engine. Note that duplicates will cause issues so using if_sheet_exists='replace' is your friend.
with pd.ExcelWriter('comprehensive_report.xlsx', mode='a', engine='openpyxl', if_sheet_exists='replace') as writer:
df_inventory.to_excel(writer, sheet_name='Updated_Inventory', index=False)Writing Data at a Specific Starting Point
If you want to add a title or some introductory text above your table, you can use the startrow and startcol arguments to offset where your DataFrame is written in the sheet.
df_sales.to_excel(
'report_with_offset.xlsx',
sheet_name='Sales',
index=False,
startrow=2,
startcol=1
)This will leave two empty rows at the top and one empty column on the left.
Final Thoughts
Mastering how to export DataFrames to Excel is a practical skill that closes the loop between data analysis and business communication. We've seen how to use df.to_excel() for quick exports, combine multiple DataFrames into a single file with pd.ExcelWriter, and apply custom formatting with the XlsxWriter engine to create truly polished reports.
While automating reports with Python is a huge step up from manual copying and pasting, it still often involves a cycle of running a script, saving a file, and emailing it to stakeholders for review. This is where tools for creating connected, real-time dashboards can change the game entirely. With Graphed, we help you connect directly to your data sources and build live, interactive dashboards using simple natural language. Instead of exporting static .xlsx files, you can ask questions like "show me sales by region for this quarter" and instantly get a sharable visualization that's always up to date — no scripts required.
Related Articles
How to Enable Data Analysis in Excel
Enable Excel's hidden data analysis tools with our step-by-step guide. Uncover trends, make forecasts, and turn raw numbers into actionable insights today!
What SEO Tools Work with Google Analytics?
Discover which SEO tools integrate seamlessly with Google Analytics to provide a comprehensive view of your site's performance. Optimize your SEO strategy now!
Looker Studio vs Metabase: Which BI Tool Actually Fits Your Team?
Looker Studio and Metabase both help you turn raw data into dashboards, but they take completely different approaches. This guide breaks down where each tool fits, what they are good at, and which one matches your actual workflow.