使用openpyxl迁移Excel数据时出现行号范围错误求助
问题描述
我正在使用Python的openpyxl库将一个xlsx文件中的特定数据提取到另一个xlsx文件中。我定义了一个提取所需数据的函数,通过while循环调用该函数,期望遇到空单元格时停止运行,但却出现了错误:Row numbers must be between 1 and 1048576。以下是我的代码:
x=3; y=2; z=4; i=5 def line(): c1 = ws1.cell(row = z, column = 1) ws2.cell(row = y, column = 1).value = c1.value c2 = ws1.cell(row = i, column = 2) ws2.cell(row = y, column = 2).value = c2.value c3 = ws1.cell(row = i, column = x) ws2.cell(row = y, column = 3).value = c3.value while ws1.cell(row=i, column=x+2).value != "": line() y+=1 x+=2 i+=1 else: sys.exit()
请问我哪里操作出错了?
错误原因与解决方法
- 核心错误:循环终止条件只判断了目标单元格是否为空,没有限制行号
i的最大值。随着循环不断执行,i会持续递增,直到超过Excel的最大行号1048576,此时调用ws1.cell(row=i, ...)就会触发行号越界错误。 - 额外问题:函数
line()中的z变量始终是初始值4,不会随循环更新,这会导致你提取的第一列数据始终是第4行的内容,大概率不符合实际需求。 - 修复步骤:
- 在循环条件中加入行号上限判断,避免
i超出范围:while i <= 1048576 and ws1.cell(row=i, column=x+2).value != "": - 根据实际需求调整
z的更新逻辑,如果需要z和i同步递增,就在循环内添加z += 1:while i <= 1048576 and ws1.cell(row=i, column=x+2).value != "": line() y+=1 x+=2 i+=1 z+=1 # 按需添加,确保第一列数据行号同步更新 - 优化空单元格判断逻辑:openpyxl中未赋值的单元格值为
None,而非空字符串,建议改用is not None判断:while i <= 1048576 and ws1.cell(row=i, column=x+2).value is not None:
- 在循环条件中加入行号上限判断,避免
内容的提问来源于stack exchange,提问作者PulaNegro
相关产品推荐
相关产品推荐

