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

使用openpyxl时遇NoneType不可迭代错误,日期比较失败

问题分析与解决

错误根源

你遇到的argument of type 'NoneType' is not iterable错误,并非来自日期比较语句,而是出自前面的判断if "Submitted" in row[complete_index]:当row[complete_index]的值为None时,in运算符试图在不可迭代的None对象中查找字符串,直接触发报错。

你当前打印的行数据正常,但循环中必然存在某一行的row[complete_index]是None,导致代码执行到该行时抛出错误。

修复方案

  1. 先校验row[complete_index]的有效性
    在判断"Submitted"是否存在之前,先确认该值不为None,再转换为字符串进行匹配:

    if row[complete_index] is not None and "Submitted" in str(row[complete_index]):
    
  2. 增强日期比较的安全性
    虽然当前打印的日期是datetime类型,但为了避免其他行可能出现的类型异常,可以增加类型校验:

    import datetime
    # ... 其他代码 ...
    if date_submitted is not None and isinstance(date_submitted, datetime.datetime):
        today_as_datetime = datetime.datetime.today()
        if date_submitted <= today_as_datetime:
            # 执行你的逻辑
    

修改后的完整代码示例

import datetime
from openpyxl import load_workbook

wb = load_workbook(filepath)
ws = wb.active
# 读取工作表数据为二维列表
data = [row for row in ws.values]
# 获取表头
headers = data[0]
date_submitted_index = headers.index("Date Submitted")
# 假设complete_index是你定义的另一个表头索引,根据实际情况调整
complete_index = headers.index("Complete Status")

for i, row in enumerate(data[1:], start=1):
    # 先校验complete字段非空,再判断是否包含Submitted
    if row[complete_index] is not None and "Submitted" in str(row[complete_index]):
        date_submitted = row[date_submitted_index]
        print(date_submitted)
        print(type(date_submitted))
        # 校验日期非空且为datetime类型
        if date_submitted is not None and isinstance(date_submitted, datetime.datetime):
            today_as_datetime = datetime.datetime.today()
            if date_submitted <= today_as_datetime:
                # 执行你的业务逻辑
                print("符合条件的日期")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 03:41:28