I want to iterate this list in my excel file, can you show me a different way to do it?

Viewed 54

My question is simple and I'm sorry to ask it here. But I tried several ways to iterate through my excel file and I'm having trouble finding the solution.

from openpyxl import workbook, load_workbook

wb = load_workbook("italian_team.xlsx")
ws = wb.active

rows = ws["A"]

equipe = ["Juventus", "Ac Milan", "Torino", "Pescara", "As Roma", "Genoa", "Napoli"]

for cell in rows:
    x = equipe[cell]

wb.save("italian_team.xlsx")
1 Answers

Do you mean you just want to insert your list as a row in the workbook?
If so there are a few options, you could just append the list as is to the sheet in which case it will be enter after the last used row.
Or specify the row (and column) to add to.
Both options are shown in the code below

from openpyxl import workbook, load_workbook

wb = load_workbook("italian_team.xlsx")
ws = wb.active

# rows = ws["A"]

equipe = ["Juventus", "Ac Milan", "Torino", "Pescara", "As Roma", "Genoa", "Napoli"]

# for cell in rows:
#     x = equipe[cell]

#  This will append the list after the last used row
ws.append(equipe)    

#  This will enter the list at row 1 column 1 to the length of the list
#  Use min_row = and max_col = as well if the list is to be on another row or start at another column 
for row in ws.iter_rows(max_row=1, max_col=len(equipe)):
    for enum, cell in enumerate(row):
        cell.value = equipe[enum]

wb.save("italian_team.xlsx") 
Related