[英]Why am I getting IndexError: list index out of range
from openpyxl import load_workbook
book = load_workbook('Line_Machines_Data.xlsx')
sheet = book['Line 7 machines']
line_7data = [15, 20, 30, 40] # this is the new data
for row in sheet['A1' : 'F1']: #iterates through each row
for count, cell in enumerate(row):
cell.value = line_7data[count]
book.save('Line_Machines_Data.xlsx')
I need the cell value to be updated using an index.我需要使用索引更新单元格值。 What could I do?我能做什么? I have already tried using the range() and len() method and creating a variable called index, but that did not iterate through like enumerate can.我已经尝试过使用 range() 和 len() 方法并创建一个名为 index 的变量,但它并没有像 enumerate 那样迭代。 Thank you!谢谢!
The error seems to suggests there are more cells you are populating in the row than they are data in your line_7data variable.该错误似乎表明您在行中填充的单元格比 line_7data 变量中的数据多。 Line_7data has four values, but you're enumerating through more than 4 cells. Line_7data 有四个值,但您正在枚举超过 4 个单元格。 After the fourth row, your code is trying to grab the fifth item in line_7data, but it doesn't exist.在第四行之后,您的代码试图获取 line_7data 中的第五项,但它不存在。
You could add additional logic to check if you have exceeded the size of your array and return before the index is out of bounds, or, as mentioned in your comment, add more data to your variable.您可以添加额外的逻辑来检查您是否超过了数组的大小并在索引超出范围之前返回,或者如您的评论中所述,将更多数据添加到您的变量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.