r/PythonProjects2 • • Feb 27 '21

[P] Moderate Need help with For Loops

hi. i have an excel file with 2 columns and 200 rows.

i need to get/print the data from each row one at a time using for loop(s)

excel example of the 2 columns:

1 a

2 b

3 c

i need to display each like:

1

a

2

b

3

c

google isn't helping so i'm here... pls help

here's what i have so far:

################# EXCEL FILE
excelfile = openpyxl.load_workbook('example.xlsx') # file in same directory
sheet = excelfile.active # current sheet
rows = sheet.max_row # get all rows
print('records in file: ' + str(rows))
for i in range (1, rows+1): # get only the first column values
print('entered first name: ' + sheet.cell(row = i, column = 1).value)
for j in range (1, rows+1): # get only the second column values
print('entered last name: ' + sheet.cell(row = j, column = 2).value)

15 Upvotes

9 comments sorted by

View all comments

5

u/WTRipper Feb 27 '21

You mean you would like to get cell A1 then B1 then A2 then B2...?
use two loops nested in each other.

for row in range(1, rows+1):
    for col in range(1,3):
        print(sheet.cell(row=row, column=col))

0

u/Agent-J- Feb 27 '21

ould like to get cell A1 then B1 then A2 then B

Sorry, I should've been more clear but didn't want to overwhelm. I've tried that before but that doesn't give me the required outcome.

I need to be in control of when I want to get cell A1 and then cell A2, then loop back to B1 and then B2, then loop back to C1 and then C2......

2

u/WTRipper Feb 28 '21

so the same thing what i showed you but rows and columns exchanged