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
Please suggest a way to access next cell value in a loop. I am using python 2.7. Thanks in advance.
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.
For instance:
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
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)
You get:
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)
You get the same result.
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).