使用openpyxl追加DataFrame到Excel触发IndexError: string index out of range
问题原因
这个IndexError: string index out of range报错来自低版本openpyxl的dataframe_to_rows函数的兼容性缺陷:当你使用的pandas版本≥1.4时,pandas返回的列数据结构发生了变化,3.0.7版本以下的openpyxl会误将整列数据识别为单个字符串,尝试按索引取对应位置值时就会触发字符串索引越界。
你测试简单DataFrame不报错是因为简单数据结构刚好符合旧版函数的解析逻辑,真实业务数据结构更复杂就触发了兼容问题。
解决方法
方案1(最稳妥,无需修改依赖)
直接替换原有追加逻辑,绕开dataframe_to_rows函数:
把代码段中:
for row in dataframe_to_rows(final_output_df, header = False, index = False): sheet.append(row)
替换为:
for row in final_output_df.values.tolist(): sheet.append(row)
该方案兼容所有版本的pandas和openpyxl,运行效率和原逻辑无差异。
方案2(保留原逻辑)
升级openpyxl到3.0.7及以上版本即可解决兼容问题:
pip install --upgrade openpyxl
可选排查项
如果执行上述方案后仍报错,可先执行以下代码清理DataFrame异常列:
# 删除全空列 final_output_df = final_output_df.dropna(axis=1, how='all') # 重置索引避免隐藏索引问题 final_output_df = final_output_df.reset_index(drop=True)
内容的提问来源于stack exchange,提问作者chuky pedro
相关产品推荐
相关产品推荐

