[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倍性能,待验证。

相关推荐
阿幸软件杂货间7 分钟前
PPT转图片拼贴工具 v4.3
python·powerpoint
寒士obj7 分钟前
Java对象创建过程
java·开发语言
Java知识库16 分钟前
「深度拆解」Spring Boot如何用DeepSeek重构MCP通信层?从线程模型到分布式推理的架构进化
java·开发语言·spring boot·程序员·编程
Bruce_Liuxiaowei20 分钟前
PHP文件读取漏洞全面剖析:触发点与利用技术
开发语言·php
摸鱼码21 分钟前
(头歌作业)-6.5 幻方(project)
开发语言·python
oioihoii33 分钟前
C++11 尾随返回类型:从入门到精通
java·开发语言·c++
Wyn_43 分钟前
【QT】qtdesigner中将控件提升为自定义控件后,css设置样式不生效(已解决,图文详情)
开发语言·qt
MYH5161 小时前
汽车停车匹配充电桩随机森林
python·随机森林·汽车
伍六星1 小时前
更新Java的环境变量后VScode/cursor里面还是之前的环境变量
java·开发语言·vscode
Dola_Pan1 小时前
Android四大组件通讯指南:Kotlin版组件茶话会
android·开发语言·kotlin