Search code examples
pythonexcelfor-loopopenpyxlvariable-variables

How do I create a dynamic variable based on the row number I am iterating over in an Excel sheet while using openpyxl?


I am trying to iterate over all the rows in an Excel worksheet and set a variable based on the cell that is currently being iterated over. Below is the code that I am using:

import openpyxl
from openpyxl import load_workbook

wb = openpyxl.load_workbook('workbook.xlsx', data_only=True)
queue = wb['Queue']
max_row = queue.max_row

for i in queue.iter_rows(min_row=2, max_row=max_row):
    dynamic_cell = queue.cell(row=i, column=10).value
    if dynamic_cell  == 'ice cream':
        # perform some operation

Initially, I thought that this article, under the section "Iterating by rows", had the answer I was looking for: https://medium.com/aubergine-solutions/working-with-excel-sheets-in-python-using-openpyxl-4f9fd32de87f

However, when I arrive at the input:

dynamic_cell = queue.cell(row=i, column=10).value

My output is:

TypeError: '<' not supported between instances of 'tuple' and 'int'

I'm unsure of how to interpret this or what other solutions to try. Any feedback on how to make dynamic_cell work would be greatly appreciated! (:

UPDATE: From what I've been able to gather, the most effective solution may be to create a list of integers based on the number of rows in max_row(see: How can you dynamically create variables via a while loop?). However, I don't have the necessary experience to accomplish this at the moment. I'll continue my search for a solution while periodically checking this post.


Solution

  • The solution, per @Charlie Clark's observation:

    import openpyxl
    from openpyxl import load_workbook
    
    wb = openpyxl.load_workbook('workbook.xlsx', data_only=True)
    queue = wb['Queue']
    max_row = queue.max_row
    
    for i in queue.iter_rows(min_row=2, max_row=max_row):
        dynamic_cell = i[9]
        if dynamic_cell  == 'ice cream':
            # perform some operation