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

如何使用openpyxl在Excel中搜索数据?TypeError运行报错排查求助

错误原因汇总

  • iter_rows()方法传参错误:你直接将范围字符串'B4:F4'传给了iter_rows(),但该方法的位置参数要求是整数类型的min_row、max_row、min_col、max_col,传入字符串自然会触发类型错误。
  • 代码缩进不符合Python语法规范,循环、判断语句的子代码没有正确缩进。
  • 业务逻辑不匹配:你的需求是查找值为Pavel的单元格,但代码里判断条件写的是== "Maria"。

修正后可运行的代码

import openpyxl
# 替换为你本地的Excel文件路径
wb = openpyxl.open('the path to the file')

# 注意openpyxl工作表索引从0开始,如果你要选第一个工作表请改为0
wb.active = 1
ws = wb.active

# 方式1:直接遍历指定范围的单元格
for row in ws['B4:F4']:
    for cell in row:
        if cell.value == "Pavel":
            # 按你的需求打印当前单元格所在行第2列的内容,要打印Pavel本身直接print(cell.value)即可
            print(ws.cell(row=cell.row, column=2).value)

# 方式2:用iter_rows传整数参数的写法
# for row in ws.iter_rows(min_row=4, max_row=4, min_col=2, max_col=6):
#     for cell in row:
#         if cell.value == "Pavel":
#             print(ws.cell(row=cell.row, column=2).value)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 15:45:01