Reputation: 3605
for row_cells in sheet.iter_rows(min_col=1, max_col=8):
for cell in row_cells:
print('%s: cell.value=%s' % (cell, cell.value))
The above snippet returns all the columns starting from column 1 up to column 8. I only need values from these two columns. Is it possible to get column 1 and 8 only? I'm not able to figure it out yet.
Upvotes: 2
Views: 7371
Reputation:
There are two ways:
for row in range(2,worksheet.max_row+1):
for column in [column_3_name, column_8_name]:
cell_name = "{}{}".format(column, row)
process(worksheet[cell_name].value) # Process it
Beware this is heavy on memory, allocating memory for each cell. See: https://openpyxl.readthedocs.io/en/2.5/tutorial.html (especially first warning).
I would choose to do what you are doing currently:
for row_cells in sheet.iter_rows(min_col=1, max_col=8):
for cell in row_cells:
# Check for column name here.
Upvotes: 0
Reputation: 114290
You aren't obligated to have the inner loop:
for row_cells in sheet.iter_rows(min_col=1, max_col=8):
print('%s: cell.value=%s' % (row_cells[0], row_cells[0].value))
print('%s: cell.value=%s' % (row_cells[-1], row_cells[-1].value))
A better approach might be to zip the iterators over just those two columns:
for c1, c8 in zip(sheet.iter_rows(min_col=1, max_col=1), sheet.iter_rows(min_col=8, max_col=8)):
print('%s: cell.value=%s' % (c1, c1.value))
print('%s: cell.value=%s' % (c8, c8.value))
Upvotes: 3