Home > Back-end >  openpyxl iter_rows only loops through the first cell
openpyxl iter_rows only loops through the first cell

Time:09-22

I am trying to compare 3 column of data in 2 separate worksheets and if the data match then copy the info on other cells over. The below code works and gets me the result I want but it only runs the first cell in A_Rows. I want it to loop through the length of A_Rows and pass in the second row of A_Rows

A_Rows = A_List.iter_rows(min_row=2,min_col=5,max_row=289,max_col=7)
B_Rows = B_List.iter_rows(min_row=2,min_col=5,max_row=48927,max_col=7)

for name,dob,gen in A_Rows:
    for name2,dob2,gen2 in B_Rows:
        d1 = dob.value.strftime('%m/%d/%Y')
        d2 = dob2.value.strftime('%m/%d/%Y')
        if str(d1)==str(d2):
            if gen.value==gen2.value:
                if name.value in name2.value.upper():
                    A_List.cell(row = name.row, column=4, value=B_List.cell(row=dob2.row, column=4).value)
                    A_List.cell(row = name.row, column=8, value=B_List.cell(row=dob2.row, column=8).value)
                    A_List.cell(row = name.row, column=9, value=B_List.cell(row=dob2.row, column=9).value)
                    A_List.cell(row = name.row, column=11, value=B_List.cell(row=dob2.row, column=11).value)

CodePudding user response:

You are initialising B_Rows once before the processing so it cylces once only. For this to work you'd need to move that iter_rows line to be inside the loop.

A_Rows = A_List.iter_rows(min_row=2,min_col=5,max_row=289,max_col=7)
# Move this into the loop
# B_Rows = B_List.iter_rows(min_row=2,min_col=5,max_row=48927,max_col=7)

for name,dob,gen in A_Rows:
    # for name2,dob2,gen2 in B_Rows: <--- is not initiated again after first loop of Row_A
    for name2,dob2,gen2 in B_List.iter_rows(min_row=2,min_col=5,max_row=48927,max_col=7)
        d1 = dob.value.strftime('%m/%d/%Y')
        d2 = dob2.value.strftime('%m/%d/%Y')
        if str(d1)==str(d2):
            if gen.value==gen2.value:
                if name.value in name2.value.upper():
                    A_List.cell(row = name.row, column=4, value=B_List.cell(row=dob2.row, column=4).value)
                    A_List.cell(row = name.row, column=8, value=B_List.cell(row=dob2.row, column=8).value)
                    A_List.cell(row = name.row, column=9, value=B_List.cell(row=dob2.row, column=9).value)
                    A_List.cell(row = name.row, column=11, value=B_List.cell(row=dob2.row, column=11).value)
  • Related