Reputation: 1011
I'm using Openpyxl. I'm open to answers using other methods/modules as well.
So to reference a cell value, you can do:
ws = wb.get_active_sheet()
for cellobject in sheet.columns[1]:
print(cellobject.value)
1001
1002
1003
1004
But what If I wanted to reference a cell in the same row, for example column C (kind of like a vlookup formula)?
| A | B |
|:-----------|------------:|
| 1001 | Cow |
| 1002 | Cat |
| 1003 | Dog |
| 1004 | Mouse |
So the end result may look something like:
(1001, Cow)
(1002, Cat)
or:
1001
Cow
1002
Cat
Upvotes: 1
Views: 942
Reputation: 11
Correction of 2. Answer: Just pass first and second columns to zip() function.
for cell01, cell02 in zip(sheet.columns[0], sheet.columns[1]):
print(cell01.value, cell02.value)
yielding "(1001, Cow)" etc.
Upvotes: 1
Reputation: 90979
You can also try going over ws.rows
, this will give you each row (complete with all the columns) one by one, example -
for row in ws.rows:
print((row[0].value, row[1].value)) #for first and second column.
or you can iterate over the row as well, to get each cell in the row. Example -
for row in ws.rows:
for cell in row:
print(cell.value) #this will print cell by cell , in a new line.
Upvotes: 2
Reputation: 174806
Just pass first and second columns to zip function.
for cellobject1, cellobject2 in zip(sheet.columns[1], sheet.columns[1]):
print((cellobject1.value, cellobject2.value))
Upvotes: 1