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. Thank you!

>Solution :

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 has four values, but you’re enumerating through more than 4 cells. After the fourth row, your code is trying to grab the fifth item in line_7data, but it doesn’t exist.

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.

Leave a Reply