使用 for 和 if 遍历 openpyxl 中的行

Using for and if to iterate through rows in openpyxl

我一直在四处寻找,但找不到明显的问题答案。

我正在使用 openpyxl 通过以下调用使用 read_only = True 从 sheets 读取数据:

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

但是,我想跳过 sheet 中的第一行,想知道是否可以在第一个 for 调用中执行此操作,看起来像这样:

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

显然这是行不通的。唯一的其他方法是在行调用之后执行 if 例如:

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

这看起来很麻烦。指导将不胜感激。

P.

如何切掉第一行?

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

注意:这是未经测试的,但从 source code.

可以看出

您可以直接使用迭代器跳过第一行。

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

在我的例子中,需要使用 iter_rows 方法,如下例所示:

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

我使用的是 openpyxl 版本 3.0.0