Paul
Paul

Reputation: 982

Using for and if to iterate through rows in openpyxl

I have been searching around but could not find an obvious answer to my problem.

I am using openpyxl to read data from sheets with read_only = True through the following call:

for row in ws.rows:
    for col in row:
          npAvailability[row_idx, col_idx] = col.value
          col_idx += 1
    row_idx += 1

However, I want to skip the first row in the sheet and was wondering if it is possible to do this in the first for call that may look something like this:

for row in ws.rows if row_idx >= 1:

Obviously this does not work. The only other way is to do the if after the row call eg:

for row in ws.row:
    if row_idx >= 1:
         for col in row:
             etc...

This seems cumbersome. Guidance would be appreciated.

P.

Upvotes: 1

Views: 4978

Answers (3)

Shan
Shan

Reputation: 399

In my case using iter_rows method was required, as with example below:

wb = openpyxl.load_workbook(test_file)
ws = wb.active
for row in ws.iter_rows(min_row=2):
    print(row)

I was using openpyxl version 3.0.0

Upvotes: 0

Ron Norris
Ron Norris

Reputation: 2690

You can skip the first row by using the iterator directly.

iter = ws.iter_rows
# Start at row 2
for row_idx in range(2, ws.max_row):
    for col_idx,col in enumerate(iter(str(row_idx)), 1):
        for cell in col:
            npAvailability[row_idx, col_idx] = cell.value

Upvotes: 0

Kind Stranger
Kind Stranger

Reputation: 1761

What about slicing off the first row?

for row in ws.rows[1:]:
    ...

NOTE: this is untested but look right from the source code.

Upvotes: 2

Related Questions