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

23,228

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.

Share:
23,228
chakolatemilk
Author by

chakolatemilk

Computer Science student. Learning more from this website than I do at school. Thanks to everyone who has ever helped me in any problem I've had!

Updated on January 07, 2022

Comments

  • chakolatemilk
    chakolatemilk over 2 years

    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!

  • chakolatemilk
    chakolatemilk about 7 years
    Okay, I'm not sure why I didn't think to modify it this way... But I just did it and I ended up modifying it a bit more but I think I got what I needed. Thank you!