Search code examples
pythonexcelopenpyxlnested-loops

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


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 

Solution

  • 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)