使用Openpyxl按条件复制Excel数据报错:IndexError: list index out of range
解决Excel复制指定行时的IndexError问题
问题背景
需求:当Excel表格B列中存在用户名“Administrator”时,将该行数据完整复制到另一个新的Excel工作簿。
运行代码时触发错误:
IndexError: list index out of range
原代码如下:
def copyRange(startCol, startRow, endCol, endRow, sheet): rangeSelected = [] #Loops through selected Rows for i in range(startRow,endRow + 1,1): #Appends the row to a RowSelected list rowSelected = [] for j in range(startCol,endCol+1,1): if (sheet.cell(row = i, column = j).value) in adminlist: rowSelected.append(sheet.cell(row = i, column = j).value) #Adds the RowSelected List and nests inside the rangeSelected rangeSelected.append(rowSelected) return rangeSelected def pasteRange(startCol, startRow, endCol, endRow, sheetReceiving, copiedData): countRow = 0 for i in range(startRow,endRow+1,1): countCol = 0 for j in range(startCol,endCol+1,1): sheetReceiving.cell(row = i, column = j).value = copiedData[countRow][countCol] countCol += 1 countRow += 1 selectedRange = copyRange(1, 1, 13, sheet.max_row, sheet) #Change the 4 number values pasteRange(1, 1, 13, sheet.max_row, Users_sheet, selectedRange) #Change the 4 number values
错误原因分析
copyRange逻辑偏离需求且产生空列表:原函数遍历所有列,仅把匹配adminlist的单元格加入rowSelected,导致非目标行的rowSelected是空列表;而需求是B列值为Administrator时复制整行,不是筛选单元格。pasteRange遍历行数不匹配:粘贴时遍历原表的总行数,但copiedData里只有符合条件的行,且存在空列表项,访问copiedData[countRow][countCol]时必然触发索引越界。
修正后的代码
def copyAdminRows(startCol, endCol, sheet, target_name="Administrator"): rangeSelected = [] # 遍历每一行,从第1行到最后一行 for i in range(1, sheet.max_row + 1): # 检查B列(column=2)的值是否为目标用户名 b_col_value = sheet.cell(row=i, column=2).value if b_col_value == target_name: row_data = [] # 复制当前行的所有指定列数据 for j in range(startCol, endCol + 1): row_data.append(sheet.cell(row=i, column=j).value) rangeSelected.append(row_data) return rangeSelected def pasteRows(startCol, startRow, sheetReceiving, copiedData): countRow = 0 # 仅遍历实际复制到的行数 for row_data in copiedData: countCol = 0 for col_value in row_data: sheetReceiving.cell(row=startRow + countRow, column=startCol + countCol).value = col_value countCol += 1 countRow += 1 # 调用函数:复制第1到13列,筛选B列是Administrator的行 selectedRange = copyAdminRows(1, 13, sheet) # 粘贴到目标工作表的起始位置(第1行第1列) pasteRows(1, 1, Users_sheet, selectedRange)
修正说明
copyAdminRows:专门针对B列做判断,符合条件才复制整行的指定列数据,避免空列表加入结果。pasteRows:根据copiedData的实际行数遍历,确保索引不会越界,同时简化了列的遍历逻辑。- 移除了冗余的行范围参数,直接使用
sheet.max_row获取总行数,更灵活。
内容的提问来源于stack exchange,提问作者Edw
相关产品推荐
相关产品推荐

