文件说明
xlsx_readers_complete.py - 完整版本,包含所有库的详细示例
simple_examples.py - 简化版本,只包含核心代码
requirements.txt - 所有依赖库列表
readme.md - 本说明文档
库分类和推荐
最推荐的库
| 库名 | 特点 | 适用场景 |
|---|---|---|
| pandas | 功能最强大,生态最完善 | 数据分析、数据科学项目 |
| openpyxl | 专门处理excel,功能全面 | 纯excel文件处理 |
| polars | 高性能,内存效率高 | 大数据处理 |
专业库
| 库名 | 特点 | 适用场景 |
|---|---|---|
| xlwings | 与excel应用程序交互 | 需要excel高级功能 |
| pyexcel | 统一接口,支持多种格式 | 多格式文件处理 |
| tablib | 数据导入导出 | 数据转换和导出 |
高性能库
| 库名 | 特点 | 适用场景 |
|---|---|---|
| fastexcel | 基于rust,速度快 | 大文件快速读取 |
| calamine | rust实现,高性能 | 性能要求极高的场景 |
| dask | 并行计算 | 超大文件处理 |
| modin | 加速pandas | pandas性能优化 |
| vaex | 大数据可视化 | 亿级数据处理 |
传统库
| 库名 | 特点 | 适用场景 |
|---|---|---|
| xlrd | 传统excel读取库 | 老项目维护(注意版本兼容性) |
| xlutils | excel工具集 | 配合xlrd使用 |
快速开始
最简单的方法(推荐)
import pandas as pd
# 读取xlsx文件每一行为列表
df = pd.read_excel('your_file.xlsx')
rows = df.values.tolist() # 不包含列名
# 或者包含列名:
rows_with_headers = [df.columns.tolist()] + df.values.tolist()
不依赖pandas的方法
from openpyxl import load_workbook
workbook = load_workbook('your_file.xlsx')
sheet = workbook.active
rows = [list(row) for row in sheet.iter_rows(values_only=true)]
自动选择库的方法
def read_xlsx_auto(filename):
"""自动选择可用的库来读取xlsx文件"""
try:
import pandas as pd
df = pd.read_excel(filename)
return [df.columns.tolist()] + df.values.tolist()
except importerror:
from openpyxl import load_workbook
workbook = load_workbook(filename)
sheet = workbook.active
return [list(row) for row in sheet.iter_rows(values_only=true)]
安装依赖
最小安装(适合大多数场景)
pip install pandas openpyxl
完整安装(所有库)
pip install -r requirements.txt
按需安装
数据分析场景:
pip install pandas openpyxl xlwings
高性能场景:
pip install polars fastexcel
大数据场景:
pip install dask[complete] modin[all] vaex
注意事项
- xlrd版本问题:xlrd 2.0+ 不再支持xlsx格式,如需使用请安装1.2.0版本
- xlwings依赖:需要安装microsoft excel应用程序
- rust库:calamine和fastexcel可能需要rust编译环境
- 内存使用:大文件建议使用polars、dask等高性能库
- 兼容性:某些库在不同操作系统上的表现可能不同
选择建议
新手/通用项目:使用 pandas
纯excel处理:使用 openpyxl
高性能需求:使用 polars 或 fastexcel
大数据处理:使用 dask 或 vaex
与excel交互:使用 xlwings
多格式支持:使用 pyexcel
性能对比
| 库名 | 小文件(<1mb) | 中文件(1-100mb) | 大文件(>100mb) | 内存使用 |
|---|---|---|---|---|
| pandas | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐ | 中等 |
| openpyxl | ⭐⭐⭐ | ⭐⭐ | ⭐ | 较高 |
| polars | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | 低 |
| fastexcel | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | 低 |
| xlrd | ⭐⭐⭐ | ⭐⭐ | ⭐ | 中等 |
示例数据格式
所有示例都假设xlsx文件包含以下数据:
| 姓名 | 年龄 | 城市 |
|---|---|---|
| 张三 | 25 | 北京 |
| 李四 | 30 | 上海 |
| 王五 | 35 | 广州 |
读取后的列表格式:
[
['姓名', '年龄', '城市'], # 列名(如果包含)
['张三', 25, '北京'],
['李四', 30, '上海'],
['王五', 35, '广州']
]
完整代码
"""
所有可以读取xlsx文件的python库大全
每个库都提供读取xlsx文件每一行为列表的代码示例
"""
# ============================================================================
# 1. pandas - 最流行的数据分析库
# ============================================================================
def read_xlsx_with_pandas():
"""使用pandas读取xlsx文件"""
import pandas as pd
# 读取xlsx文件
df = pd.read_excel('example.xlsx')
# 方法1: 转换为列表的列表
rows_as_lists = df.values.tolist()
# 方法2: 包含列名的方式
rows_with_headers = [df.columns.tolist()] + df.values.tolist()
# 方法3: 逐行读取
rows = []
for index, row in df.iterrows():
rows.append(row.tolist())
return rows_as_lists
# ============================================================================
# 2. openpyxl - 专门处理excel文件的库
# ============================================================================
def read_xlsx_with_openpyxl():
"""使用openpyxl读取xlsx文件"""
from openpyxl import load_workbook
# 加载工作簿
workbook = load_workbook('example.xlsx')
sheet = workbook.active # 或者 workbook['sheet1']
# 读取所有行为列表
rows = []
for row in sheet.iter_rows(values_only=true):
rows.append(list(row))
return rows
# ============================================================================
# 3. xlrd - 传统的excel读取库
# ============================================================================
def read_xlsx_with_xlrd():
"""使用xlrd读取xlsx文件"""
import xlrd
# 打开工作簿
workbook = xlrd.open_workbook('example.xlsx')
sheet = workbook.sheet_by_index(0) # 或者 workbook.sheet_by_name('sheet1')
# 读取所有行
rows = []
for row_idx in range(sheet.nrows):
row = []
for col_idx in range(sheet.ncols):
row.append(sheet.cell_value(row_idx, col_idx))
rows.append(row)
return rows
# ============================================================================
# 4. xlwings - 与excel应用程序交互的库
# ============================================================================
def read_xlsx_with_xlwings():
"""使用xlwings读取xlsx文件"""
import xlwings as xw
# 打开excel应用程序和工作簿
app = xw.app(visible=false)
workbook = app.books.open('example.xlsx')
sheet = workbook.sheets[0]
# 获取使用区域的数据
used_range = sheet.used_range
rows = used_range.value
# 如果只有一行数据,确保返回列表的列表
if isinstance(rows[0], (int, float, str)):
rows = [rows]
# 关闭工作簿和应用程序
workbook.close()
app.quit()
return rows
# ============================================================================
# 5. pyexcel - 统一的电子表格接口
# ============================================================================
def read_xlsx_with_pyexcel():
"""使用pyexcel读取xlsx文件"""
import pyexcel
# 直接读取为列表的列表
rows = pyexcel.get_records(file_name='example.xlsx')
# 转换为纯列表格式
if rows:
# 获取列名
headers = list(rows[0].keys())
result = [headers]
# 添加数据行
for record in rows:
result.append([record[header] for header in headers])
return result
return []
# ============================================================================
# 6. xlsxwriter + openpyxl 组合 (xlsxwriter主要用于写入,这里用openpyxl读取)
# ============================================================================
def read_xlsx_with_xlsxwriter_openpyxl():
"""xlsxwriter主要用于写入,读取仍使用openpyxl"""
# xlsxwriter主要用于创建xlsx文件,读取功能有限
# 通常与openpyxl结合使用
return read_xlsx_with_openpyxl()
# ============================================================================
# 7. python-excel - 另一个excel处理库
# ============================================================================
def read_xlsx_with_python_excel():
"""使用python-excel读取xlsx文件"""
# 注意:python-excel通常指的是xlrd/xlwt/xlutils的组合
# 对于xlsx文件,推荐使用xlrd
return read_xlsx_with_xlrd()
# ============================================================================
# 8. tablib - 表格数据处理库
# ============================================================================
def read_xlsx_with_tablib():
"""使用tablib读取xlsx文件"""
import tablib
# 读取xlsx文件
with open('example.xlsx', 'rb') as f:
dataset = tablib.dataset().load(f, format='xlsx')
# 转换为列表的列表
rows = []
if dataset.headers:
rows.append(dataset.headers)
for row in dataset:
rows.append(list(row))
return rows
# ============================================================================
# 9. xlutils - excel工具集合
# ============================================================================
def read_xlsx_with_xlutils():
"""使用xlutils读取xlsx文件"""
# xlutils主要用于xls文件,对xlsx支持有限
# 建议使用openpyxl或pandas
return read_xlsx_with_openpyxl()
# ============================================================================
# 10. ezodf - opendocument格式库(也支持xlsx)
# ============================================================================
def read_xlsx_with_ezodf():
"""使用ezodf读取xlsx文件"""
# ezodf主要用于odf格式,对xlsx支持有限
# 建议使用专门的xlsx库
return read_xlsx_with_openpyxl()
# ============================================================================
# 11. pyexcel-xlsx - pyexcel的xlsx插件
# ============================================================================
def read_xlsx_with_pyexcel_xlsx():
"""使用pyexcel-xlsx读取xlsx文件"""
import pyexcel_xlsx
import pyexcel
# 读取xlsx文件
sheet = pyexcel.get_sheet(file_name='example.xlsx')
# 转换为列表的列表
rows = []
for row in sheet:
rows.append(list(row))
return rows
# ============================================================================
# 12. xlrd3 - xlrd的python 3版本
# ============================================================================
def read_xlsx_with_xlrd3():
"""使用xlrd3读取xlsx文件"""
# xlrd3是xlrd的分支,用法基本相同
return read_xlsx_with_xlrd()
# ============================================================================
# 13. calamine-python - rust calamine的python绑定
# ============================================================================
def read_xlsx_with_calamine():
"""使用calamine读取xlsx文件"""
try:
from calamine import calamineworkbook
# 打开工作簿
workbook = calamineworkbook.from_path('example.xlsx')
# 读取第一个工作表
sheet_names = workbook.sheet_names
if sheet_names:
sheet = workbook.get_sheet_by_name(sheet_names[0])
rows = []
for row in sheet.iter_rows():
rows.append(list(row))
return rows
except importerror:
print("calamine库未安装,使用openpyxl替代")
return read_xlsx_with_openpyxl()
# ============================================================================
# 14. fastexcel - 快速excel读取库
# ============================================================================
def read_xlsx_with_fastexcel():
"""使用fastexcel读取xlsx文件"""
try:
import fastexcel
# 读取excel文件
df = fastexcel.read_excel('example.xlsx')
# 转换为列表的列表
rows = df.values.tolist()
# 添加列名作为第一行
if hasattr(df, 'columns'):
rows.insert(0, df.columns.tolist())
return rows
except importerror:
print("fastexcel库未安装,使用pandas替代")
return read_xlsx_with_pandas()
# ============================================================================
# 15. polars - 高性能数据处理库
# ============================================================================
def read_xlsx_with_polars():
"""使用polars读取xlsx文件"""
try:
import polars as pl
# 读取xlsx文件
df = pl.read_excel('example.xlsx')
# 转换为列表的列表
rows = df.to_numpy().tolist()
# 添加列名作为第一行
rows.insert(0, df.columns)
return rows
except importerror:
print("polars库未安装,使用pandas替代")
return read_xlsx_with_pandas()
# ============================================================================
# 16. dask - 并行计算库
# ============================================================================
def read_xlsx_with_dask():
"""使用dask读取xlsx文件"""
try:
import dask.dataframe as dd
# dask不直接支持xlsx,需要先用pandas读取
import pandas as pd
df = pd.read_excel('example.xlsx')
# 转换为dask dataframe
ddf = dd.from_pandas(df, npartitions=1)
# 计算并转换为列表
rows = ddf.compute().values.tolist()
return rows
except importerror:
print("dask库未安装,使用pandas替代")
return read_xlsx_with_pandas()
# ============================================================================
# 17. modin - 加速pandas的库
# ============================================================================
def read_xlsx_with_modin():
"""使用modin读取xlsx文件"""
try:
import modin.pandas as pd
# 读取xlsx文件
df = pd.read_excel('example.xlsx')
# 转换为列表的列表
rows = df.values.tolist()
return rows
except importerror:
print("modin库未安装,使用pandas替代")
return read_xlsx_with_pandas()
# ============================================================================
# 18. vaex - 大数据处理库
# ============================================================================
def read_xlsx_with_vaex():
"""使用vaex读取xlsx文件"""
try:
import vaex
import pandas as pd
# vaex不直接支持xlsx,需要先用pandas读取
df_pandas = pd.read_excel('example.xlsx')
# 转换为vaex dataframe
df_vaex = vaex.from_pandas(df_pandas)
# 转换为列表的列表
rows = df_vaex.to_pandas_df().values.tolist()
return rows
except importerror:
print("vaex库未安装,使用pandas替代")
return read_xlsx_with_pandas()
# ============================================================================
# 使用示例和测试函数
# ============================================================================
def create_sample_xlsx():
"""创建示例xlsx文件用于测试"""
import pandas as pd
# 创建示例数据
data = {
'姓名': ['张三', '李四', '王五'],
'年龄': [25, 30, 35],
'城市': ['北京', '上海', '广州']
}
df = pd.dataframe(data)
df.to_excel('example.xlsx', index=false)
print("已创建示例文件 example.xlsx")
def test_all_readers():
"""测试所有读取方法"""
# 创建示例文件
create_sample_xlsx()
readers = [
("pandas", read_xlsx_with_pandas),
("openpyxl", read_xlsx_with_openpyxl),
("xlrd", read_xlsx_with_xlrd),
("pyexcel", read_xlsx_with_pyexcel),
("tablib", read_xlsx_with_tablib),
("pyexcel-xlsx", read_xlsx_with_pyexcel_xlsx),
("calamine", read_xlsx_with_calamine),
("fastexcel", read_xlsx_with_fastexcel),
("polars", read_xlsx_with_polars),
("dask", read_xlsx_with_dask),
("modin", read_xlsx_with_modin),
("vaex", read_xlsx_with_vaex),
]
for name, reader_func in readers:
try:
print(f"\n=== 使用 {name} 读取 ===")
rows = reader_func()
for i, row in enumerate(rows):
print(f"第{i+1}行: {row}")
except exception as e:
print(f"{name} 读取失败: {e}")
if __name__ == "__main__":
# 运行测试
test_all_readers()
到此这篇关于python读取xlsx文件的所有python库大全(附代码)的文章就介绍到这了,更多相关python读取xlsx内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论