Python3使用calamine库处理超大Excel文件
作者:码农丁丁
calamine`是一个用于读取多种电子表格格式(如 Excel、LibreOffice Calc 等)的 Python 库。它支持 `.xls`, `.xlsx`, `.ods` 和 `.csv` 文件格式,提供了简单易用的 API 来加载和处理电子表格数据。calamine`的一大特点是它的轻量级和高效性,特别适合需要快速解析电子表格而不依赖于重量级库(如 `openpyxl` 或 `pandas`)的应用场景。
安装
要使用 calamine,首先需要通过 pip安装它:
pip3 install calamine
基本用法
读取 Excel 文件
以下是如何使用 calamine 读取 Excel 文件并获取其中的数据:
from calamine import Workbook, CellType
# 打开工作簿
workbook = Workbook.open("example.xlsx")
# 获取所有的工作表名称
sheet_names = workbook.sheet_names()
print(f"Sheet names: {sheet_names}")
# 选择第一个工作表
sheet = workbook.get_sheet_by_index(0)
# 遍历所有行
for row in sheet.rows():
# 每一行是一个列表,包含每个单元格的值
print([cell.value for cell in row if cell.type != CellType.EMPTY])
# 关闭工作簿
workbook.close()读取 ODS 文件
对于 OpenDocument Spreadsheet (ODS) 文件,操作方式类似:
from calamine import Workbook, CellType
# 打开 ODS 工作簿
workbook = Workbook.open("example.ods")
# 选择第一个工作表
sheet = workbook.get_sheet_by_index(0)
# 遍历所有行
for row in sheet.rows():
print([cell.value for cell in row if cell.type != CellType.EMPTY])
# 关闭工作簿
workbook.close()读取 CSV 文件
虽然 CSV 文件不是严格意义上的电子表格文件,但 `calamine` 同样可以方便地处理它们:
from calamine import Workbook, CellType
# 打开 CSV 文件
with open("example.csv", "r") as f:
workbook = Workbook.from_csv(f)
# 选择唯一的工作表
sheet = workbook.get_sheet_by_index(0)
# 遍历所有行
for row in sheet.rows():
print([cell.value for cell in row if cell.type != CellType.EMPTY])处理单元格类型
calamine`支持多种单元格类型,并允许你根据需要访问不同类型的数据:
from calamine import CellType
# 假设我们已经打开了一个工作簿并选择了某个工作表
for row in sheet.rows():
for cell in row:
if cell.type == CellType.STRING:
print(f"String value: {cell.value}")
elif cell.type == CellType.NUMBER:
print(f"Number value: {cell.value}")
elif cell.type == CellType.BOOL:
print(f"Boolean value: {cell.value}")
elif cell.type == CellType.ERROR:
print(f"Error value: {cell.error}")
elif cell.type == CellType.FORMULA:
print(f"Formula: {cell.formula}, Result: {cell.value}")
elif cell.type == CellType.EMPTY:
print("Empty cell")获取特定单元格的值
如果你知道具体的单元格位置(例如 A1),可以直接获取其值:
# 获取 A1 单元格的值
value = sheet.get_value("A1")
print(f"Value at A1: {value}")更多高级功能
遍历列:除了按行遍历外,还可以按列遍历。
合并单元格:支持检测和处理合并的单元格。
样式信息:尽管 calamine`主要关注数据本身,但它也提供了一些基础的样式信息访问方法。
公式计算:如果需要计算公式的结果,可以在读取时指定参数来启用此功能。
示例:完整代码示例
以下是一个完整的例子,演示了如何使用 `calamine` 读取 Excel 文件中的数据,并进行简单的数据处理:
from calamine import Workbook, CellType
def read_excel(file_path):
workbook = Workbook.open(file_path)
sheet = workbook.get_sheet_by_index(0)
data = []
for row in sheet.rows():
row_data = [cell.value for cell in row if cell.type != CellType.EMPTY]
if row_data:
data.append(row_data)
workbook.close()
return data
if __name__ == "__main__":
file_path = "example.xlsx"
data = read_excel(file_path)
# 打印前几行数据作为示例
for row in data[:5]:
print(row)Python calamine处理超大EXcel文件
为什么选择 Calamine?
相较于 openpyxl 等传统库,python-calamine 在处理大规模数据时有碾压性的性能优势。
| 库/引擎 | 读取 50 万行数据的耗时 | 性能对比 |
|---|---|---|
| Calamine | 约 3.58 秒 | 基准 (最快) |
| Pandas + Calamine | 约 7 - 9.4 秒 | 约 2-3 倍于纯 Calamine |
| openpyxl | 约 2 分钟 | 约 10 倍于 Calamine |
注意:不同测试场景下的数据会略有差异,但 Calamine 的领先地位非常明确。
如何安装与使用
1. 安装
通过 pip 即可轻松安装:
pip install python-calamine
如果你的项目主要使用 Pandas,只需安装 python-calamine 库,Pandas 即可自动识别并使用它。
2. 基础用法:直接使用 CalamineWorkbook
这是最直接的方式,适合对性能有极致要求,或不想引入 Pandas 依赖的场景。
from python_calamine import CalamineWorkbook
# 加载 Excel 文件
workbook = CalamineWorkbook.from_path("your_large_file.xlsx")
# 获取所有工作表名称
sheet_names = workbook.sheet_names
print(sheet_names)
# 按名称获取工作表,并将其转换为 Python 列表
sheet_data = workbook.get_sheet_by_name("Sheet1").to_python()
# 遍历数据
for row in sheet_data:
print(row)关键点:to_python() 方法默认会跳过数据区域前后的空行和空列,提高效率。
3. 进阶用法:与 Pandas 结合(推荐)
如果你习惯使用 Pandas 进行数据分析,最便捷的方式是在 pd.read_excel() 中指定 engine="calamine"。
import pandas as pd
# 方法一:读取文件路径
df = pd.read_excel("your_large_file.xlsx", engine="calamine")
# 方法二:读取文件对象(推荐,可避免路径问题)
with open("your_large_file.xlsx", "rb") as f:
df = pd.read_excel(f, sheet_name="Sheet1", engine="calamine")你还可以结合 usecols 参数,只读取需要的列,进一步提升性能。
# 只读取 A 到 N 列
df = pd.read_excel("large_file.xlsx", usecols="A:N", engine="calamine")总结
calamine 是一个非常轻便且高效的工具,适用于需要快速解析多种格式电子表格的应用程序。它提供的 API 简单直观,易于集成到现有项目中。10倍性能,待验证。
到此这篇关于Python3使用calamine库处理超大Excel文件的文章就介绍到这了,更多相关Python calamine处理Excel内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
