如何加速Python读取Excel文件的性能_使用calamine引擎替代openpyxl

如何加速Python读取Excel文件的性能_使用calamine引擎替代openpyxl

Python

启用calamine引擎需满足pandas>=2.2.0且安装calamine-python;通过storage_options={"engine": "calamine"}隐式触发,不支持engine参数直传,仅加速读取、不支持写入与样式。

pd.read_excel() 怎么启用 calamine 引擎

必须满足两个硬性条件:pandas>=2.2.0 且安装 calamine-python(不是 calamine)。calamine 是 Rust 库,Python 绑定叫 calamine-python,装错就直接报 ImportError: Unable to find calamine library

安装命令是:

pip install "pandas>=2.2.0" calamine-python

启用方式非常隐蔽:不能靠 engine 参数显式传入(那样会报 ValueError: Unknown engine 'calamine'),而是靠 storage_options 隐式触发:

  • 读取单个 sheet 时,用 pd.read_excel("file.xlsx", storage_options={"engine": "calamine"})
  • 读取多个 sheet 时,先创建 pd.ExcelFile("file.xlsx", storage_options={"engine": "calamine"}),再调用 .parse()

注意:storage_options 这个参数本意是传给底层文件系统(如 S3),但 pandas 2.2+ 把它复用为 calamine 的开关——文档没写,IDE 不提示,属于“靠源码或 issue 发现”的隐藏机制。

为什么 calamine 比 openpyxl 快 10 倍

根本差异不在 Python 层,而在数据解析模型:openpyxl 是纯 Python 实现的 XML 解析器,要解压 .xlsx、逐层遍历 XML 节点、重建单元格对象;calamine 是 Rust 写的二进制解析器,直接跳过 XML DOM 构建,按 Excel 内部结构(如 SharedStrings、SheetData)做内存映射式读取。

这意味着:

Python 3.14.3

微软官方的 Python 扩展,是 VS Code 安装量最高的扩展(209M+)。集成 IntelliSense(通过 Pylance)、调试(通过 Python Debugger)、代码检查、格式化、重构和单元测试等功能。支持 Jupyter Notebook、虚拟环境管理和多 Python 版本切换。

  • 对 50 万行 × 50 列的文件,openpyxl 耗时主要卡在 XML 解析(占 40%)和对象实例化(每 cell 一个 openpyxl.cell.cell.Cell 对象)
  • calamine 不生成任何中间 cell 对象,直接返回 numpy 数组或 pandas Series,跳过类型推断阶段
  • 它不支持样式、公式、合并单元格等——不是 bug,是设计取舍。如果你的 Excel 里有大量条件格式或 =SUM(A:A),calamine 会静默忽略,只读数值/字符串原始值

读取多 sheet 或获取 sheet 名称时怎么绕过性能陷阱

直接用 pd.ExcelFile(file).sheet_names 会触发完整文件加载(哪怕你只想要名字),在 10MB+ 文件上可能卡 20 秒以上。这不是 pandas 的锅,是 openpyxl 默认行为:打开即解析整个 workbook.xml。

真正轻量的方案是绕过 pandas,直接用 zipfile 解析:

import zipfile
from xml.etree import ElementTree as ET

def get_xlsx_sheet_names(file_path):
with zipfile.ZipFile(file_path) as zf:
with zf.open("xl/workbook.xml") as f:
tree = ET.parse(f)
root = tree.getroot()
return [s.get("name") for s in root.iter("{http://schemas.openxmlformats.org/spreadsheetml/2006/main}sheet")]

这个函数读 14MB 文件只要 0.04 秒,且完全不依赖 openpyxlcalamine。但它只适用于 .xlsx,对 .xls.xlsb 无效——后者得用 xlrdon_demand=True 模式。

calamine 不能写的坑:to_excel 还在用 openpyxl

目前(pandas 2.2.x)所有 df.to_excel() 调用仍强制走 openpyxl,无论你是否装了 calamine-python。这意味着:

  • 想提速写入?没门。50 万行导出仍要 2 分钟
  • 不能靠 “读用 calamine + 写用 calamine” 实现端到端加速
  • 如果流程是「读→清洗→写」,瓶颈永远在最后一步,此时应考虑换格式:用 df.to_parquet()df.to_feather() 替代 Excel 输出

官方明确说 calamine 写支持要等到 pandas 3.0(预计 2026 年中发布),在此之前,别指望它能替代 openpyxl 的全部能力——它只解决最痛的那个点:读大文件慢。

本文地址:https://www.sztg.com.cn/article/676451.html

如非特殊说明,本站内容均来自于网友自主分享,如有任何问题均请联系我们进行处理!

猜您喜欢