Chris Chris - 5 months ago 8
Python Question

Use excel row with specific value openpyxl

I'm trying to find a row in an excel sheet that has a certain value and then work with the cells in that row.

So for example, I want to find the row that has a value of "Yes" in column A. I've tried to do this with the following code (hoping it would print the number of the row with "Yes" in it), but nothing gets printed when I try this code:

wb = openpyxl.load_workbook('C:\\rtemp\\Names.xlsx')
ws = wb['Sheet5']
strValue="Yes"

for row in range(1, 5):
for column in "A":
cell_name = "{}{}".format(column, row)
value= str(ws[cell_name].value)
if value==strValue:
rownum=row
print(rownum)


Please can someone help with what I'm doing wrong

Answer

The following works on my machine, no matter if "Yes" is after row 5 or not.

strValue="Yes"

for row in range(ws.max_row):
    for column in "A":
        cell_name = "{}{}".format(column, row+1)
        value= str(ws[cell_name].value)
        if value==strValue:
            rownum = row
            print(rownum)
Comments