有没有一种简单的方法可以在 openpyxl 中迭代 Excel sheet 的不相交范围?

Is there a simple way to iterate over a disjoint range of Excel sheet in openpyxl?

我需要迭代具有 'A1', 'O1', 'R1:S1' 结构的 不相交范围 。 有很多工作簿,每个工作簿的相应 sheet 中有很多行要迭代(例如,'Sheet1' 的第 21、24、31:35、40 行)。 有没有一种简单的方法可以使用 openpyxl 或其他库对其进行迭代?

目前我对每一行都使用以下内容,这是不可接受的。

wb = openpyxl.load_workbook(filename)

sheet = wb['Sheet1']
for cellObj in sheet['A1:S2']:
    for cell in cellObj:
        pass

我在文档中找不到提示。 在这种情况下可能有其他库或不同的方法适用吗?

我不相信库中有内置的东西,但你可以这样做:

wb = openpyxl.load_workbook(filename)
sheet = wb['Sheet1']

rows = [21, 24] + list(range(31, 36) + [40]
cols = ["A", "O", "R", "S"]

for row in rows:
    for col in cols:
        cell = sheet[f"{col}{row}"]

在这种情况下RS是连续的所以没有太大问题。如果您有更大的范围手动编写会很乏味,请查看如何创建 character range 并以与 rows.

相同的方式使用它

stovfl 所述,字符串格式可能更昂贵。由于我们有单元格的行和列,我们可以使用 Worksheet.cell 方法进行简单的转换:

from openpyxl.utils.cell import column_index_from_string

...
cols = ["A", "O", "R", "S"]
cols = [column_index_from_string(col) for col in cols]
...
        cell = sheet.cell(row=row, col=col)
  • 当然,如果您首先使用整数表示法 cols,则不需要转换,访问将作为最后一行代码。