Reputation: 1571
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
Upvotes: 1
Views: 3896
Reputation: 16958
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)
Upvotes: 0
Reputation: 19497
If you are only looking for a single value this is best approach.
sentinel = u"Yes"
for row in ws:
for cell in row:
if cell.value == sentinel:
print(cell.row) #
break
If you are likely to be looking for several values then creating a dictionary of cell coordinates keyed by value is the best approach.
Upvotes: 1