pandas read_excel and to_excel: Read and Write Excel Files Without Losing Data

Sooner or later, the data you need arrives as an Excel workbook: a report with a title above the table, several sheets, codes that start with zero and a column of dates typed by hand. pandas reads and writes these files with two functions, read_excel() and to_excel(), but their defaults are tuned for clean, single-sheet files. This guide shows the arguments that matter for real workbooks, and the conversions that silently change your data on the way in or out.
All examples were run on 23 November 2026 with pandas 3.1.1, openpyxl 3.1.5 and Python 3.13. They behave the same on pandas 2.x, except that text columns show as object instead of str.
Install an engine first
pandas does not parse Excel files itself. It hands the work to an "engine", and for .xlsx files the default is openpyxl. Without it, the first call fails with a clear message:
ImportError: `Import openpyxl` failed. Use pip, conda, or your preferred package management tool to install the openpyxl package.
python -m pip install pandas openpyxl
Install it inside the project's virtual environment, so the dependency is recorded with the rest of the project. Two other engines are worth knowing. xlrd now reads only the old .xls format. calamine, added in pandas 2.2, reads .xlsx, .xls, .xlsb and .ods files through a Rust library; the pandas 2.2 release notes cite benchmarks "up to 5x faster than 'openpyxl'" for reading. Install python-calamine and pass engine="calamine" to use it. Writing .xlsx still goes through openpyxl or XlsxWriter.
Reading the right sheet and the right rows
Our example workbook, sales.xlsx, has two sheets. The first, Summary, starts with a title line, a date line and an empty row before the table. Read it with no arguments and pandas takes the first sheet and treats its first row as the header:
import pandas as pd
df = pd.read_excel("sales.xlsx")
print(df.head(3))
# Quarterly sales report Unnamed: 1 Unnamed: 2 Unnamed: 3 Unnamed: 4
# 0 Generated 2026-11-23 NaN NaN NaN NaN
# 1 NaN NaN NaN NaN NaN
# 2 region q1 q2 q3 q4
Unnamed: 1 columns are the sign that the header is in the wrong place. Skip the lines above the table with skiprows (or point at the header row with header=3), and choose the sheet by name with sheet_name:
df = pd.read_excel("sales.xlsx", sheet_name="Summary", skiprows=3)
print(df)
# region q1 q2 q3 q4
# 0 North 120 135 150 170
# 1 South 98 101 97 110
# 2 East 143 150 162 158
# only columns A to C, only the first two data rows
pd.read_excel("sales.xlsx", sheet_name="Summary", skiprows=3, usecols="A:C", nrows=2)
sheet_name also accepts a position (0 is the first sheet), a list, or None. With None you get every sheet at once, as a dictionary of DataFrames keyed by sheet name, which is the quickest way to inspect an unfamiliar workbook:
sheets = pd.read_excel("sales.xlsx", sheet_name=None)
list(sheets) # ['Summary', 'Orders']
orders = sheets["Orders"]
If several sheets share the same columns, such as one sheet per month, pd.concat(sheets.values(), keys=sheets.keys()) stacks them into one table, as shown in our guide to merge, join and concat.
Keep codes as text: the leading-zero trap
The Orders sheet holds postal codes stored in Excel as text, including 01234 and 02100. pandas looks at the column, sees digits, and converts it to integers:
orders = pd.read_excel("sales.xlsx", sheet_name="Orders")
print(orders)
# order_id date zip amount
# 0 A-001 2026-10-03 1234 19.9
# 1 A-002 2026-10-04 75011 250.0
# 2 A-003 NaT 2100 NaN
orders.dtypes["zip"] # int64
The leading zeros are gone, and they cannot be recovered reliably afterwards. The same happens to product references, account numbers and phone numbers. The fix is to declare the type when reading, along with the placeholders you use for missing values and the date columns:
orders = pd.read_excel(
"sales.xlsx",
sheet_name="Orders",
dtype={"zip": str, "order_id": str},
na_values=["n/a", "-"],
parse_dates=["date"],
)
print(orders)
# order_id date zip amount
# 0 A-001 2026-10-03 01234 19.9
# 1 A-002 2026-10-04 75011 250.0
# 2 A-003 NaT 02100 NaN
Notice that the n/a in the amount column became NaN even in the first read: it is in pandas' default list of missing markers, like an empty cell. A dash is not, which is why it is added to na_values here. Our article on pandas missing values covers what those gaps then do to sums and means. Dates stored as real Excel dates come back as datetime64 values without a time zone; if they represent local times, attach one with the methods from our guide to datetime and zoneinfo.
The problem is not unique to pandas. Excel itself converts some text that looks like a date, and the consequences can be serious: in 2020, The Verge reported that scientists had renamed 27 human genes, such as MARCH1, which Excel turned into "1-Mar". MARCH1 became MARCHF1 under new guidelines from the HUGO Gene Nomenclature Committee. The 2016 study in Genome Biology cited in that coverage found gene name errors in the supplementary files of roughly a fifth of the papers it screened.
Writing a DataFrame to Excel
For a single table, to_excel() is enough. Pass index=False unless the index carries information, otherwise you get an extra unnamed column of row numbers:
summary = pd.read_excel("sales.xlsx", sheet_name="Summary", skiprows=3)
summary["total"] = summary[["q1", "q2", "q3", "q4"]].sum(axis=1)
summary.to_excel("report.xlsx", sheet_name="Totals", index=False)
Writing does not preserve your types for the next reader. The zip column written as text is read back as int64 unless the reading code also passes dtype. If the file is meant for another program rather than a person, a CSV with an agreed encoding is often the safer format; reading such files is covered in fixing UnicodeDecodeError in read_csv.
Keep the size limits in mind too. Microsoft's Excel specifications cap a worksheet at 1,048,576 rows by 16,384 columns, and to_excel() raises an error rather than truncate a larger DataFrame.
Several sheets in one file
Calling to_excel("report.xlsx") twice overwrites the file each time. To write several sheets, open an ExcelWriter and pass it to each call. Inside the with block you also have access to the openpyxl worksheet, which lets you freeze the header and widen columns:
with pd.ExcelWriter("report.xlsx", engine="openpyxl") as writer:
summary.to_excel(writer, sheet_name="Totals", index=False)
orders.to_excel(writer, sheet_name="Orders", index=False)
ws = writer.sheets["Totals"]
ws.freeze_panes = "B2"
for col in ws.columns:
width = max(len(str(c.value)) for c in col if c.value is not None) + 2
ws.column_dimensions[col[0].column_letter].width = width
list(pd.read_excel("report.xlsx", sheet_name=None)) # ['Totals', 'Orders']
The openpyxl documentation lists the other formatting options (fonts, number formats, conditional formatting). Keep that part small: a report whose layout depends on fifty lines of formatting code is easier to maintain as an Excel template that the script fills in.
Adding a sheet to an existing workbook
To add or replace one sheet without rewriting the others, open the writer in append mode. The if_sheet_exists argument decides what happens when the sheet is already there:
top = summary.nlargest(1, "total")
with pd.ExcelWriter("report.xlsx", mode="a", engine="openpyxl",
if_sheet_exists="replace") as writer:
top.to_excel(writer, sheet_name="Best region", index=False)
list(pd.read_excel("report.xlsx", sheet_name=None))
# ['Totals', 'Orders', 'Best region']
Without if_sheet_exists, a second run fails with ValueError: Sheet 'Best region' already exists and if_sheet_exists is set to 'error'. The other choices are "new" (create Best region1), "replace" and "overlay" (write over the existing cells). Append mode works only with openpyxl. Close the file in Excel before running the script: on Windows an open workbook is locked and the write raises a PermissionError.
A short checklist
- Look before you load:
sheet_name=Noneto list the sheets, thenskiprowsorheaderuntil the column names are right. - Declare
dtype=strfor every code or identifier column, andna_valuesfor your placeholders. - Write with
index=False, and use oneExcelWriterfor several sheets. - Use
mode="a"with an explicitif_sheet_existsto update a workbook in place. - Build file paths with
pathlibrather than string concatenation when the script runs on several machines.
The full list of arguments is in the pandas reference for read_excel, to_excel and ExcelWriter.
DataMissing values (NaN)
Recognise placeholders when reading a CSV, count gaps with isna, choose between dropna, fillna and interpolate, and see how NaN changes sums, means and groupby.
Datapandas groupby
Split, apply, combine: totals per group, named aggregation, transform, filter and the defaults that changed in pandas 3.
DataUnicodeDecodeError in read_csv
Why pd.read_csv raises UnicodeDecodeError: 'utf-8' codec can't decode byte, and how to fix it with the right encoding, BOM handling and UTF-8 conversion.