openpyxl-循环读取下一个单元格值 [英] openpyxl - Reading a next cell value in a loop

查看:582
本文介绍了openpyxl-循环读取下一个单元格值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个循环来遍历工作表中的单元格.在某些情况下,我想循环访问下一个单元格值.

I am creating an loop to traverse the cells in sheet. At some conditions i want to access next cell value in a loop.

import openpyxl

wb = openpyxl.load_workbook('test.xlsx')
wb = wb.get_sheet_by_name("Sheet 1")


for row in wb['A1' : 'B150']:
    for cell in row:
        print cell.value  # prints current active cell
        if something:
            # print next cell value

请提出一种循环访问下一个单元格值的方法.我正在使用python 2.7.提前致谢.

Please suggest a way to access next cell value in a loop. I am using python 2.7. Thanks in advance.

推荐答案

好吧,这不是特定于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).

这篇关于openpyxl-循环读取下一个单元格值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆