-1

I got an error:

NameError: name 'sheet' is not defined .I wanna parse excel and print the content.

My wrote codes:

class ReadData():
    def __init__(self, sheet_path):
        self.book = xlrd.open_workbook(sheet_path)
        self.sheet = self.book.sheet_by_index(1)
        self.companies = []

    def read(self):
        for row_index in range(2, sheet.nrows):
            rows = sheet.row_values(row_index)
            print(rows)

x = ReadData('./data/excel1.xlsx')
x.read()

I really cannot understand why this error happens.Should I add something to use init ?How can I fix this?

aircraft
  • 25,146
  • 28
  • 91
  • 166
user8563636
  • 163
  • 1
  • 5
  • 12

4 Answers4

1

You should use self.sheet instead of just sheet. So update your method as

def read(self):
    # ------------------------v
    for row_index in range(2, self.sheet.nrows):
       #---------v
        rows = self.sheet.row_values(row_index)
        print(rows)
Rohan
  • 52,392
  • 12
  • 90
  • 87
1

in read function, there is no sheet defined. you should use self.sheet.nrows

Max
  • 1,283
  • 9
  • 20
0

Try this

class ReadData():
    def __init__(self, sheet_path):
        self.book = xlrd.open_workbook(sheet_path)
        self.sheet = self.book.sheet_by_index(1)
        self.companies = []

    def read(self):
        for row_index in range(2, self.sheet.nrows):
            rows = self.sheet.row_values(row_index)
            print(rows)

x = ReadData('./data/excel1.xlsx')
x.read()

I added a self. ahead of sheet at line 8

Old Panda
  • 1,466
  • 2
  • 15
  • 30
0

The error itself says that it can not find an attribute sheet in your read() method. You have used sheet at two places: 1: In for loop's range 2: In the first line of for loop.

If you want to use any attribute inside any method in python, then it can be only a class variable or a local variable or an instance variable or some imported attribute.

class variable or instance variable can be accessed via self.

In your case, sheet is an instance variable and hence it can be only accessed using self.

So if you change those two occurrences of sheet by self.sheet, it would work.

Here is your corrected code

class ReadData(object):
    def __init__(self, sheet_path):
        self.book = xlrd.open_workbook(sheet_path)
        self.sheet = self.book.sheet_by_index(1)
        self.companies = []

    def read(self):
        for row_index in range(2, self.sheet.nrows):
            rows = self.sheet.row_values(row_index)
            print(rows)

x = ReadData('./data/excel1.xlsx')
x.read()
Amit Yadav
  • 1,861
  • 2
  • 20
  • 27