-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

2
  • Possible duplicate of Read Excel File in Python Commented Nov 28, 2017 at 16:37
  • Please give your complete code and the complete error message. Commented Nov 28, 2017 at 16:37

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.