Analyst
Analyst

Reputation: 137

Iterate through sheets in Pyexcel in python

I want to iterate through all the non empty sheets of Excel to get the headers. I must use PyExcel for that.Here is my code:

import pyexcel as pe
book = pe.get_book(file_name="Mydata.xlsx")




j=0
print(j)
for j in range(100):
    for item in book.sheet_by_index(j):

     sheet = pe.get_sheet(file_name="Mydata.xlsx")
     sheetheaders= sheet.row_at(0)
     header_list = [i for i in sheetheaders if i != '' ]

     print(header_list)
     j=j+1

Can anyone help me by telling how do I iterate it without getting following error?

Traceback (most recent call last):
   line 11, in <module>
    for sheet in book[i]:
TypeError: 'NoneType' object is not iterable

Thank you!

Upvotes: 0

Views: 339

Answers (2)

chfw
chfw

Reputation: 4592

Please try this:

import pyexcel as p

header_list = [[ a_header for a_header in sheet.row[0] if a_header] for sheet in p.get_book(file_name="my file.xlsx") if sheet.number_of_rows() > 0]

Upvotes: 1

darksky
darksky

Reputation: 2090

You do not need to increment the index manually in a for loop. Try the following code:

for sheet_index in range(book.number_of_sheets()):
    sheet = book.sheet_by_index(sheet_index)
    header_list = [header for header in sheet.row_at(0)]

    print(header_list)

Upvotes: 1

Related Questions