openpyxl - Iterate over columns and rows to grab data from middle of sheet

chakolatemilk picture chakolatemilk · Apr 25, 2017 · Viewed 19k times · Source

I'm reading the documentation for openpyxl, and I needed something a bit more specific and I wasn't sure if there's a way to do it using iter_rows or iter_cols.

In the docs, it said to do this to grab rows and cols:

for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
  for cell in row:
    print(cell)

or

for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
  for cell in col:
    print(cell)

Doing this will give me A1, B1, C1 and so on or A1, A2, B1, B2, and so on.

But is there a way to manipulate this so you can grab the data from another point in the sheet?

I'm trying to grab the cells from F3 to W3 for example. But I'm not sure how many rows there are, there could be 5, there could be 10. So I would need to grab F4 to W4 and so on until I reach the last one which could be F10 to W10 or something.

I understand how the iter_rows and iter_cols work but I haven't found a way to manipulate it to start elsewhere and to reach an end if there are no other values left? It appears I would have to define the max_rows to how many rows there are in the sheet. Is there a way for it to check for the max amount of rows itself?

The biggest question I have is just how to iterate through the rows starting in the middle of the sheet rather than the beginning. It doesn't have to use iter_rows or iter_cols, that's just the part I was reading up on most in the documentation.

Thank you in advance!

Answer

Charlie Clark picture Charlie Clark · Apr 25, 2017

What's wrong with ws.iter_cols(min_row=3, min_col=6, max_col=23) for ws[F3:W…]? If no maximum is specified openpyxl will keep iterating as far as it can.