You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将基于xlrd的Excel遍历代码转换为openpyxl实现?

把xlrd遍历Excel的代码改为openpyxl版本

以下是适配openpyxl的修改后代码,完全保留原逻辑:

import os
from openpyxl import load_workbook

file_path = os.path.join(root_dir, fname)
# read_only=True优化大文件读取性能,data_only=True读取单元格值而非公式(和xlrd默认行为一致)
wb = load_workbook(file_path, read_only=True, data_only=True)
sname_found = False

# 遍历所有工作表,用enumerate同时拿到索引和工作表对象
for sheet_index, sheet in enumerate(wb.worksheets):
    sname_row = None
    # openpyxl行索引从1开始,循环覆盖所有有效行
    for row_index in range(1, sheet.max_row + 1):
        row = sheet[row_index]
        for cell in row:
            cell_text = cell.value
            # 转换为原代码的0-based行索引,不需要的话可直接用row_index
            sname_row = row_index - 1
            sheet_name = sheet.title  # 对应xlrd的sheet.name
            sname_found = True

关键差异说明

  • 工作簿打开:用load_workbook替代xlrd.open_workbook,read_only和data_only参数匹配xlrd的默认读取规则。
  • 工作表操作:wb.worksheets是所有工作表的列表,可直接遍历或通过索引访问(如wb.worksheets[0]),替代sheet_by_index;工作表名称用sheet.title替代sheet.name。
  • 行索引处理:openpyxl采用1-based索引,若需要和原代码的0-based索引一致,需将row_index减1。
  • 行数据获取:sheet[row_index]直接获取整行单元格,对应xlrd的sheet.row(row_index)。

内容的提问来源于stack exchange,提问作者borfo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 17:18:18