[python3]Excel解析库-calamine,10倍openpyxl性能

`calamine` 是一个用于读取多种电子表格格式(如 Excel、LibreOffice Calc 等)的 Python 库。它支持 `.xls`, `.xlsx`, `.ods` 和 `.csv` 文件格式,提供了简单易用的 API 来加载和处理电子表格数据。`calamine` 的一大特点是它的轻量级和高效性,特别适合需要快速解析电子表格而不依赖于重量级库(如 `openpyxl` 或 `pandas`)的应用场景。

安装

要使用 `calamine`,首先需要通过 `pip` 安装它:

复制代码
```bash
pip3 install calamine
```

基本用法

复制代码
#### 读取 Excel 文件

以下是如何使用 `calamine` 读取 Excel 文件并获取其中的数据:

```python
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) 文件,操作方式类似:

```python
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` 同样可以方便地处理它们:

```python
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` 支持多种单元格类型,并允许你根据需要访问不同类型的数据:

```python
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),可以直接获取其值:

```python
# 获取 A1 单元格的值
value = sheet.get_value("A1")
print(f"Value at A1: {value}")
```

### 更多高级功能

- **遍历列**:除了按行遍历外,还可以按列遍历。
- **合并单元格**:支持检测和处理合并的单元格。
- **样式信息**:尽管 `calamine` 主要关注数据本身,但它也提供了一些基础的样式信息访问方法。
- **公式计算**:如果需要计算公式的结果,可以在读取时指定参数来启用此功能。

### 示例:完整代码示例

以下是一个完整的例子,演示了如何使用 `calamine` 读取 Excel 文件中的数据,并进行简单的数据处理:

```python
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)
```

总结

`calamine` 是一个非常轻便且高效的工具,适用于需要快速解析多种格式电子表格的应用程序。它提供的 API 简单直观,易于集成到现有项目中。

10倍性能,待验证。

相关推荐
谙弆悕博士20 分钟前
多智能体架构详解:市场拍卖式架构(Market-based / 竞价协商)
开发语言·架构·去中心化·多智能体·智能体·拍卖架构
ShineWinsu36 分钟前
对于Qt:QMessageBox的解析
开发语言·c++·qt·面试·客户端·qmessagebox·消息对话框
承渊政道1 小时前
【Python编程快速上手—让繁琐工作自动化】(列表:把数据排成队,从下标取值到深拷贝)
开发语言·python·pycharm·自动化·列表
大胖爱学习_MJ1 小时前
Agent 如何安全地拿数据库密码?基于 HashiCorp Vault 的动态凭证下发
经验分享·python
tryCbest2 小时前
Python 爬虫从入门到实战(一):基础篇——从零写出第一个爬虫
开发语言·爬虫·python
无小道2 小时前
Python语句的特色
python·语句
多加点辣也没关系2 小时前
JavaScript|第40章:JavaScript 工程化实践
开发语言·javascript·ecmascript
2601_967980113 小时前
python pytest如何编写测试
python·测试用例·pytest·函数·assert
2601_967980114 小时前
Python中heapq模块的各种用法实例
数据结构·python·算法·应用实例·heapq模块
大胖爱学习_MJ4 小时前
超越向量检索:用 Spring Boot + Neo4j 手搓 GraphRAG 知识图谱记忆
java·后端·python