且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

openpyxl-循环读取下一个单元格值

更新时间:2022-02-07 06:46:18

好吧,这不是特定于OpenPyXl的问题,而是有关迭代器的问题.

Well, this is not an OpenPyXl specific question, but more a question about iterators.

您可以做的是编写一个对序列进行迭代并返回当前项和下一项的函数.

What you can do is write a function which iterates over a sequence and returns the current and the next item.

例如:

def iter_curr_next(seq):
    iter_seq = iter(seq)
    curr_item = next(iter_seq)
    next_item = next(iter_seq)  # may raise StopIteration
    yield curr_item, next_item
    while True:
        curr_item = next_item
        next_item = next(iter_seq)  # may raise StopIteration
        yield curr_item, next_item

注意:此函数返回对(curr_item,next_item)直到最后一个对.

Note: this function returns the couples (curr_item, next_item) until the last but one.

这里是如何使用此功能的方法(例如,当当前为奇数时,我们显示当前和下一项):

Here is how you can use this function (for instance, we display the current and next item when the current is an odd number):

row = [1, 2, 3, 5, 6, 5]

for curr_item, next_item in iter_curr_next(row):
    if curr_item % 2 == 1:
        print(curr_item, next_item)

您得到:

1 2
3 5
5 6

但是,这有点复杂...

But, this is a little complex…

您可以做的是创建一个列表(或元组)并以这种方式对其进行迭代:

What you can do instead is to create a list (or a tuple) and iterate on it that way:

for curr_item, next_item in zip(row[:-1], row[1:]):
    if curr_item % 2 == 1:
        print(curr_item, next_item)

您得到相同的结果.

如果实际上,当您使用OpenPyXl迭代工作表的行时,每一行都是一个元组.因此,上一个for循环将起作用(请参阅:openpyxl.worksheet.worksheet.Worksheet.get_squared_range函数的实现).

If fact, when you iterate the rows of a sheet with OpenPyXl, each row is a tuple. So, the previous for loop will work (see: implementation of openpyxl.worksheet.worksheet.Worksheet.get_squared_range function).