How to run Kivy and the XLRD module properly

236 Views Asked by At

I am attempting to make a very simple app in Kivy using the xlrd module. I have an excel spreadsheet with some data and I want to show the cell (2,1) as a label. Here is my code so far:

import kivy
kivy.require('1.9.1')
import xlrd
from kivy.app import App
from kivy.uix.label import Label


class MyApp(App):
    workbook = xlrd.open_workbook('Actuarial program for BAM.xlsx')
    sheet = workbook.sheet_by_index(0)

    def build(self):
        return Label(text='sheet.cell_value(2,1)')


if __name__ == '__main__':
    MyApp().run()

First of all I understand that the label will only give me the literal text sheet.cell_value(2,1). My problem lies with the workbook and sheet variables. If I try to run the program nothing happens. However, if I comment the two lines out ('workbook =', and 'sheet ='), then the program will run, opening up a window from Kivy with the text sheet.cell_value(2,1). Is there a problem with the way I have formatted the code?

Additionally, the excel file is in the same directory as the .py program.

1

There are 1 best solutions below

4
On

Label(text='sheet.cell_value(2,1)') displays sheet.cell_value(2,1) literally since it's quoted. You have to unquote it, and since sheet is a class member, you have to prefix it by self or MyApp. I'd go with the self prefix for instance:

class MyApp(App):
    workbook = xlrd.open_workbook('Actuarial program for BAM.xlsx')
    sheet = workbook.sheet_by_index(0)

    def build(self):
        return  Label(text=self.sheet.cell_value(2,1))

if the xlsx file is in the same directory as the program I'd recommend this (and would catch exceptions & display them):

    # find out where is the script/executable installed
    program_dir = os.path.dirname(sys.executable if getattr( sys, 'frozen', False ) else __file__)
    try:
        # open the file from the same directory so script works from any cwd
        workbook = xlrd.open_workbook(os.path.join(program_dir,'Actuarial program for BAM.xlsx'))
    except Exception as e:
          print("Exception occurred: {}".format(str(e)))