for sheetname in wb.sheetnames: sheet = wb[sheetname] # 判断sheet表是否为“总行” if sheetname == "总行": # 读取表头为“接收人工号”和“推送内容”的数据 for row in sheet.rows: values = [cell.value for cell in row] if not any(values): continue # 读取表头 if not headers: headers = values receiver_index = headers.index('接收人工号') push_content_index = [i for i, header in enumerate(headers) if '推送内容' in header] continue # 读取数据 receiver = values[receiver_index] for index in push_content_index: push_content = values[index] if push_content: strtext += push_content # 将数据存储到字典中 data_dict[receiver] = strtext strtext = '' 报错argument of type "nonetype" is not iterable 有表头“接收人工号”,和“推送内容”表头,不过“推送内容”为合并单元格,不知道会不会是读到空的表头造成的,代码怎么改进
时间: 2024-03-05 09:55:08 浏览: 20
根据错误提示可以看出是因为 `push_content_index` 变量为 `None` 导致的,而 `push_content_index` 是通过查找包含“推送内容”文本的表头来确定的。因此,可以检查一下表格中是否真正存在包含“推送内容”文本的表头,或者将查找表头的代码进行改进。
具体的代码改进方案如下:
```python
for row in sheet.rows:
values = [cell.value for cell in row]
if not any(values):
continue
if sheetname == "总行":
# 读取表头
if not headers:
headers = values
receiver_index = headers.index('接收人工号')
push_content_index = [i for i, header in enumerate(headers) if '推送内容' in str(header)]
continue
# 读取数据
receiver = values[receiver_index]
for index in push_content_index:
push_content = values[index]
if push_content:
strtext += push_content
# 将数据存储到字典中
data_dict[receiver] = strtext
strtext = ''
```
在上述改进中,我们对查找表头的代码做了修改,使用了 `str()` 函数将表头数据转换为字符串类型,以避免在查找时出现类型不匹配的问题。