Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas Excel File Operations

Pandas Excel File Operations

Pandas provides rich Excel file operation features, helping us easily read and write .xls and .xlsx files, supporting complex operations such as multiple sheets, indexes, and column selection; it is an essential tool in data analysis.

Operation Method Description
Read Excel files pd.read_excel() Read an Excel file, returning a DataFrame
Write a DataFrame to Excel DataFrame.to_excel() Write a DataFrame to an Excel file
Load an Excel file pd.ExcelFile() Load an Excel file and access multiple sheets
Write multiple sheets with ExcelWriter pd.ExcelWriter() Write multiple DataFrames to different sheets of the same Excel file

pd.read_excel() - 读取 Excel 文件

pd.read_excel() method is used to read data from an Excel file and load it as a DataFrame. It supports reading .xls and .xlsx format files.

The syntax format is as follows:

pandas.read_excel(io, sheet_name=0, *, header=0, names=None, index_col=None, usecols=None, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, parse_dates=False, date_parser=, date_format=None, thousands=None, decimal='.', comment=None, skipfooter=0, storage_options=None, dtype_backend=, engine_kwargs=None)

Parameter Description:

This article takes runoob_pandas_data.xlsx as an example; you canDownload runoob_pandas_data.xlsx to test.

Example

import pandas as pd

# Read the data.xlsx file
df = pd.read_excel('runoob_pandas_data.xlsx')

# Print the DataFrame that was read
print(df)

The output is:

      表格 1 Unnamed: 1   Unnamed: 2

0     Name        Age         City

1    Alice         25     New York

2      Bob         30  Los Angeles

3  Charlie         35      Chicago

read_excel reads the first sheet by default (sheet_name=0). Assuming the data.xlsx file has only one sheet, the read data is stored in a DataFrame.

If the data.xlsx file has multiple sheets, you can read data from a specific sheet by specifying sheet_name, for example pd.read_excel('data.xlsx', sheet_name='Sheet1')。

Example

import pandas as pd

# Read the default first sheet
df = pd.read_excel('data.xlsx')
print(df)

# Read the contents of a specified sheet (by sheet name)
df = pd.read_excel('data.xlsx', sheet_name='Sheet1')
print(df)

# Read multiple sheets, returning a dictionary
dfs = pd.read_excel('data.xlsx', sheet_name=['Sheet1', 'Sheet2'])
print(dfs)

# Customize column names and skip the first two rows
df = pd.read_excel('data.xlsx', header=None, names=['A', 'B', 'C'], skiprows=2)
print(df)

DataFrame.to_excel() - Write a DataFrame to an Excel file

to_excel() method is used to write a DataFrame to an Excel file and supports .xls and .xlsx format.

The syntax format is as follows:

DataFrame.to_excel(excel_writer, *, sheet_name='Sheet1', na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, startrow=0, startcol=0, engine=None, merge_cells=True, inf_rep='inf', freeze_panes=None, storage_options=None, engine_kwargs=None)

Parameter Description:

Example

import pandas as pd

# Create a simple DataFrame
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
})

# Write the DataFrame to an Excel file, into the 'Sheet1' sheet
df.to_excel('output.xlsx', sheet_name='Sheet1', index=False)

# Write multiple sheets using ExcelWriter
with pd.ExcelWriter('output.xlsx') as writer:
df.to_excel(writer, sheet_name='Sheet1', index=False)
df.to_excel(writer, sheet_name='Sheet2', index=False)

ExcelFile - Load an Excel file

ExcelFile is a class for reading Excel files; it can handle multiple sheets and access their data without reopening the file.

The syntax format is as follows:

excel_file = pd.ExcelFile('data.xlsx')

Common methods:

Method Description
sheet_names Return a list of the names of all sheets in the file
parse(sheet_name) Parse a specified sheet and return a DataFrame
close() Close the file to release resources

Example

import pandas as pd

# Load an Excel file using ExcelFile
excel_file = pd.ExcelFile('data.xlsx')

# View the names of all sheets
print(excel_file.sheet_names)

# Read a specified sheet
df = excel_file.parse('Sheet1')
print(df)

# Close the file
excel_file.close()

ExcelWriter - Write Excel files

ExcelWriter is a class provided by pandas for writing DataFrame or Series objects to Excel files. With ExcelWriter, you can write multiple worksheets into a single Excel file and control the writing process more flexibly.

The syntax format is as follows:

pandas.ExcelWriter(path, engine=None, date_format=None, datetime_format=None, mode='w', storage_options=None, if_sheet_exists=None, engine_kwargs=None)

Parameter Description:

Create an ExcelWriter object:

Example

with ExcelWriter('output.xlsx') as writer:
    df.to_excel(writer, sheet_name='Sheet1')

Here, ExcelWriter is used as a context manager to ensure the file is properly closed after the operation completes.

Write multiple worksheets:

You can use the same ExcelWriter object to write different DataFrames to different worksheets of the same Excel file.

Example

df1 = pd.DataFrame([["AAA", "BBB"]], columns=["Spam", "Egg"])  
df2 = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"])  
with pd.ExcelWriter("path_to_file.xlsx") as writer:
    df1.to_excel(writer, sheet_name="Sheet1")  
    df2.to_excel(writer, sheet_name="Sheet2")

Set date or datetime formats:

Example

from datetime import date, datetime  
df = pd.DataFrame(
    [
        [date(2014, 1, 31), date(1999, 9, 24)],
        [datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)],
    ],
    index=["Date", "Datetime"],
    columns=["X", "Y"],
)  
with pd.ExcelWriter(
    "path_to_file.xlsx",
    date_format="YYYY-MM-DD",
    datetime_format="YYYY-MM-DD HH:MM:SS"
) as writer:
    df.to_excel(writer)

Append content to an existing Excel file:

Example

with pd.ExcelWriter("path_to_file.xlsx", mode="a", engine="openpyxl") as writer:
    df.to_excel(writer, sheet_name="Sheet3")

Use the if_sheet_exists parameter to replace an existing worksheet:

Example

with ExcelWriter(
    "path_to_file.xlsx",
    mode="a",
    engine="openpyxl",
    if_sheet_exists="replace",
) as writer:
    df.to_excel(writer, sheet_name="Sheet1")

Write multiple DataFrames to the same worksheet; note that the if_sheet_exists parameter must be set to overlay:

Example

with ExcelWriter("path_to_file.xlsx",
    mode="a",
    engine="openpyxl",
    if_sheet_exists="overlay",
) as writer:
    df1.to_excel(writer, sheet_name="Sheet1")
    df2.to_excel(writer, sheet_name="Sheet1", startcol=3)

Store an Excel file in memory:

Example

import io
df = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"])
buffer = io.BytesIO()
with pd.ExcelWriter(buffer) as writer:
    df.to_excel(writer)

Package an Excel file into a zip archive:

Example

import zipfile  
df = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"])  
with zipfile.ZipFile("path_to_file.zip", "w") as zf:
    with zf.open("filename.xlsx", "w") as buffer:
        with pd.ExcelWriter(buffer) as writer:
            df.to_excel(writer)

Pass extra parameters to the underlying engine:

Example

with pd.ExcelWriter(
    "path_to_file.xlsx",
    engine="xlsxwriter",
    engine_kwargs={"options": {"nan_inf_to_errors": True}}
) as writer:
    df.to_excel(writer)

In append mode, engine_kwargs is passed to openpyxl's load_workbook:

Example

with pd.ExcelWriter(
    "path_to_file.xlsx",
    engine="openpyxl",
    mode="a",
    engine_kwargs={"keep_vba": True}
) as writer:
    df.to_excel(writer, sheet_name="Sheet2")