Pandas pd.read_excel() function
read_excel() is a function in the pandas library for reading Excel files; it supports .xlsx and .xls format Excel files.
Excel is the most commonly used file format in enterprise data analysis; it supports multiple worksheets, rich cell formatting, formulas, and more.read_excel() can read data from Excel files and convert it into a pandas DataFrame, making subsequent processing and analysis convenient.
Basic syntax and parameters
Syntax format
pandas.read_excel(io, sheet_name=0, header=0, names=None, index_col=None,
usecols=None, dtype=None, skiprows=None, nrows=None,
na_values=None, ...)
Parameter Description
| Parameters | Type | Description | Default value |
|---|---|---|---|
| io | str, ExcelFile, path object, file-like object | the Excel file path or an ExcelFile object | Required |
| sheet_name | str, int, list, None | the name or index of the worksheet to read; None reads all worksheets | 0 |
| header | int, list of int | the row number to use as column names; 0 means the first row | 0 |
| names | list-like | a custom list of column names | None |
| index_col | int, str | Column used as the row index | None |
| usecols | int, str, list | read only the specified columns | None |
| dtype | dict | specify the data types of columns | None |
| skiprows | list-like, int | skip the specified rows | None |
| nrows | int | read only the first n rows | None |
Return Value
- Return Type:
pd.DataFrameordictof DataFrames - When
sheet_nameWhen it is a single worksheet, a DataFrame is returned. - When
sheet_nameWhen it is None or contains multiple worksheets, a dictionary is returned, with worksheet names as keys and the corresponding DataFrames as values.
Example
Through the following examples, fully master read_excel() its various usages.
Example 1: read a local Excel file
First, create and read a simple Excel file.
Example
import
pandas
as
pd
import
openpyxl
Need to install: pip install openpyxl
Create a DataFrame
data
=
{
'name'
:
[
'Tom'
,
'Jerry'
,
'Mike'
,
'Lucy'
]
,
'age'
:
[
28
,
35
,
42
,
26
]
,
'city'
:
[
'Beijing'
,
'Shanghai'
,
'Guangzhou'
,
'Shenzhen'
]
,
'salary'
:
[
8000
,
12000
,
15000
,
7000
]
}
df_original
=
pd.
DataFrame
(
data
)
Write a DataFrame to an Excel file
Excel file path: employees.xlsx
df_original.
to_excel
(
'employees.xlsx'
,
index
=
False
,
engine
=
'openpyxl'
)
Read the Excel file using read_excel
io: file path (required)
df
=
pd.
read_excel
(
'employees.xlsx'
)
View the reading result
(
"DataFrame read:"
)
(
df
)
(
"ndata types:"
)
(
df.
dtypes
)
Expected output:
读取的 DataFrame:
name age city salary
0 Tom 28 Beijing 8000
1 Jerry 35 Shanghai 12000
2 Mike 42 Guangzhou 15000
3 Lucy 26 Shenzhen 7000
Data type:
name object
age int64
city object
salary int64
Code analysis:
pd.read_excel('employees.xlsx')is the most basic usage; simply pass in the file path.- By default, the first worksheet is read (sheet_name=0) and the first row is used as column names.
- Installation required
openpyxllibrary to support reading and writing .xlsx format.
Example 2: read multiple worksheets
An Excel file can contain multiple worksheets,read_excel() supports flexibly reading specified worksheets or all worksheets.
h2 class="example">Example
import
pandas
as
pd
Create an Excel file containing multiple worksheets
First create two DataFrames
df_sales
=
pd.
DataFrame
(
{
'product'
:
[
'A'
,
'B'
,
'C'
,
'D'
]
,
'quantity'
:
[
100
,
200
,
150
,
80
]
,
'price'
:
[
50
,
30
,
40
,
60
]
}
)
df_inventory
=
pd.
DataFrame
(
{
'product'
:
[
'A'
,
'B'
,
'C'
,
'D'
]
,
'stock'
:
[
500
,
300
,
400
,
200
]
,
'warehouse'
:
[
'WH1'
,
'WH2'
,
'WH1'
,
'WH3'
]
}
)
Write multiple worksheets to one Excel file
with
pd.
ExcelWriter
(
'multi_sheet.xlsx'
,
engine
=
'openpyxl'
)
as
writer:
df_sales.
to_excel
(
writer
,
sheet_name
=
'Sales'
,
index
=
False
)
df_inventory.
to_excel
(
writer
,
sheet_name
=
'Inventory'
,
index
=
False
)
Example 2a: read a specified worksheet (by name)
df_sales_read
=
pd.
read_excel
(
'multi_sheet.xlsx'
,
sheet_name
=
'Sales'
)
(
"read the Sales worksheet:"
)
(
df_sales_read
)
(
)
Example 2b: read a specified worksheet (by index)
df_inv_read
=
pd.
read_excel
(
'multi_sheet.xlsx'
,
sheet_name
=
1
)
(
"read the 2nd worksheet (index 1):"
)
(
df_inv_read
)
(
)
Example 2c: read all worksheets (returns a dictionary)
all_sheets
=
pd.
read_excel
(
'multi_sheet.xlsx'
,
sheet_name
=
None
)
(
"all worksheet names:"
,
list
(
all_sheets.
keys
(
)
)
)
(
"niterate over all worksheets:"
)
for
sheet_name
,
df_sheet
in
all_sheets.
items
(
)
:
(
f
"n--- {sheet_name} ---"
)
(
df_sheet
)
Expected output:
Read Sales worksheet:
product quantity price
0 A 100 50
1 B 200 30
2 C 150 40
3 D 80 60
读取第2个工作表 (索引为1):
product stock warehouse
0 A 500 WH1
1 B 300 WA2
2 C 400 WH1
3 D 200 WH3
所有工作表名称: ['Sales', 'Inventory']
Iterate through all worksheets:
--- Sales ---
product quantity price
...
--- Inventory ---
product stock warehouse
...
Code analysis:
sheet_nameThe parameter accepts a worksheet name (string) or an index (integer).- Settings
sheet_name=Nonereads all worksheets and returns a dictionary, with worksheet names as keys and DataFrames as values. - Use
pd.ExcelWriterMultiple worksheets can be written conveniently.
Example 3: advanced usage - custom columns and skipped rows
In real work, Excel files may have complex formats that need flexible handling.
Example
import
pandas
as
pd
Create an Excel file with title rows and blank rows
The first few rows are metadata; the actual data starts from row 4
data_with_header
=
"""company employee data
Created: 2024-01-01
Department: Engineering
name,age,city,salary
Tom,28,Beijing,8000
Jerry,35,Shanghai,12000
"""
First create a CSV and then convert it to Excel (simulating a real scenario)
import
io
df_temp
=
pd.
read_csv
(
io.
StringIO
(
data_with_header.
split
(
'---'
)
[
1
]
)
)
df_temp.
to_excel
(
'complex_format.xlsx'
,
index
=
False
,
engine
=
'openpyxl'
)
Example 3a: skip the first few rows and use row N as column names
df_skip
=
pd.
read_excel
(
'complex_format.xlsx'
,
header
=
3
)
(
"skip the first 3 rows and use row 4 as column names:"
)
(
df_skip
)
(
)
Example 3b: read only the specified columns
df_cols
=
pd.
read_excel
(
'complex_format.xlsx'
,
usecols
=
[
'name'
,
'salary'
]
)
(
"read only the name and salary columns:"
)
(
df_cols
)
(
)
Example 3c: read only the first few rows
df_head
=
pd.
read_excel
(
'complex_format.xlsx'
,
nrows
=
2
)
(
"read only the first 2 rows:"
)
(
df_head
)
(
)
Example 3d: custom column names
df_custom_names
=
pd.
read_excel
(
'complex_format.xlsx'
,
names
=
[
'Name'
,
'Age'
,
'City'
,
'Salary'
]
,
header
=
0
)
(
"custom column names:"
)
(
df_custom_names
)
Expected output:
Skip the first 3 lines, use the 4th line as column names:
name age city salary
0 Tom 28 Beijing 8000
1 Jerry 35 Shanghai 12000
# Only read name and salary columns:
name salary
0 Tom 8000
1 Jerry 12000
Only read the first 2 lines:
name age city salary
0 Tom 28 Beijing 8000
Custom column name:
姓名 年龄 城市 薪资
0 Tom 28 Beijing 8000
1 Jerry 35 Shanghai 12000
Code analysis:
headerThe parameter specifies which row to use as column names (counting from 0).usecolsYou can specify which columns to read, using a list of names or column indexes.nrowsLimit the number of rows read, suitable for partial reading of large files.namesThe parameter lets you customize column names and overrides those in the original file.
Notes
- Reading .xlsx format requires installing
openpyxl:pip install openpyxl。 - Reading .xls format requires installing
xlrd:pip install xlrd(note: xlrd 2.0+ no longer supports .xls files). - Excel files have row and column limits (at most 1,048,576 rows and 16,384 columns); exceeding them causes data loss.
- When reading large files, consider using the
usecolsThe parameter reads only the needed columns to improve performance. sheet_nameThe parameter supports mixing names and indexes.
Summary
read_excel() is the core function in pandas for reading Excel files and is very powerful. It supports reading single or multiple worksheets and can flexibly handle Excel files in various formats.
In real data analysis work, Excel files are one of the most common data sources. Becoming proficient with read_excel() and its various parameters lets you efficiently handle all kinds of Excel data and prepare for subsequent cleaning and analysis. Readers are encouraged to practice more, especially reading multiple worksheets and configuring parameters.
Common Pandas functions