Home > database >  How to print the next row every time a function runs? (openpyxl)
How to print the next row every time a function runs? (openpyxl)

Time:01-08

The overall project I am doing is that I am taking values from a specific row and column in an excel document using openpxyl and filling out a form on a webpage. I fill the form, then save it, then fill out the next form with the next row of values from the excel document.

Excel looks like this:

First Name         Last Name         DOB

George             Hill              9/9/99
Sam                Genius            8/8/88
Bill               Smith             7/7/77

I want to run the below function three times and each time it runs prints out the next row:

 def AddFirstName():
     for i in range(3):
       for row in ws.iter_rows(min_row=1, min_col=1, max_row=3,max_col=1):
         for cell in row:
            print(cell.value)
                
            break
       break  # Tried to use breaks to break the loop so it only prints once for each loop

AddFirstName()
AddFirstName()
AddFirstName()

OR just run it outside the function like this:

    for i in range(3):
       for row in ws.iter_rows(min_row=1, min_col=1, max_row=3,max_col=1):
         for cell in row:
            print(cell.value)
                
            break
       break  # Tried to use breaks to break the loop so it only prints once for each loop

This prints:

George
George
George

How do I fix this so that it prints:

George             
Sam                
Bill 

CodePudding user response:

Check your indentation. I ran the below sample code and got the results you expect:

sheetData = [
    ['George'],
    ['Bill'],
    ['Mike']
]
for i in range(3):
    for row in sheetData:
        for cell in row:
            print(cell)
            break
    break  # indent under second 'for' 

#output:
George
Bill
Mike

If that is not the issue, check to make sure that ws.iter_rows() is really giving you a new/the next row each time through the loop. Put a break point in there and inspect / watch the value of 'row' each time through.

David

CodePudding user response:

The answer I found here

Basically, it will print out the number of rows I want pending on the amount of times I run the function.

listofnames = [
              ['George'],
              ['Bill'],
              ['Mike']]

def print_names(name):
cnt = 0
while cnt < 1:
    try:
        print(next(name))
    except StopIteration:
        print("You have reached the end of the list!")
        break
    cnt  = 1

first_name = iter(listofnames)

for i in range (3):
    print_names(first_name)
  • Related