-1

I'm trying to loop through an excel sheet printing the values in each column. Then go down to the next row, print the values of the column, until the end of the file.

My data looks like

Name           email                desc           date
name1          email1               desc1          date1
name2          email2               desc2          date2
name3          email3               desc3          date3



wb = load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
row_count = sheet.max_row -1
column_count = sheet.max_column
i = 1
while (i <= row_count):
 for item in sheet.iter_cols():
    #for row in sheet.iter_cols():
    first_value = item[i]
    print (first_value.value)
    i+=1

I get of error or tuple index out of range, and it also isn't printing the correct data.

 first_value = item[i]
 IndexError: tuple index out of range

with the code above before the out of range error i get name1, email2, desc3 as output which is clearly wrong because the data isn't in the same row

jumpman8947
  • 571
  • 1
  • 11
  • 34

2 Answers2

1

The fact that you are printing values like name1, email2, desc3 tells that you are incrementing on both column and row. This is because you are increasing the i in the nested for-loop and not in the outer one.

Try to increase it in the while loop. E.g., something like this:

while (i <= row_count):
 for item in sheet.iter_cols():
   #for row in sheet.iter_cols():
   first_value = item[i]
   print (first_value.value)
 i+=1
Vityata
  • 42,633
  • 8
  • 55
  • 100
1

The easiest way to solve this is to save your file as .csv

Then run:

import csv
with open(<YOUR_CSV_FILE_NAME>) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row)

From here you can play around with the "row" variable as you wish