PyQt打开文件对话框错误

时间:2012-08-05 12:16:15

标签: python pyqt xlrd

所以,我有一个带有QTableWidget的应用程序,想要导入一个.xls文件:

def openfile(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '/home', ".xls(*.xls)")
        fname = open(filename)
        with fname:
            wb = xlrd.open_workbook(fname)
            wb.sheet_names()
            sh = wb.sheet_by_index(0)
            for col in sh.ncols:
                for i in col:
                    r = 0
                    c = 0
                    newItem = QtGui.QTableWidgetItem(i)
                    self.tableWidget.setItem(r, c, newItem)
                    r += 1
                r = 0
                c += 1

但是,我收到此错误:TypeError: coercing to Unicode: need string or buffer, file found

我做错了什么?

更新

def openfile(self):
            filename = unicode(QtGui.QFileDialog.getOpenFileName(self, 'Open File', '', ".xls(*.xls)"))
            wb = xlrd.open_workbook(filename)
            wb.sheet_names()
            sh = wb.sheet_by_index(0)
            self.first = sh.col_values(0)
            self.r = 0
            self.add()

    def add(self):
        for i in self.first:
             str(i)
             newItem = QtGui.QTableWidgetItem(i)
             self.tableWidget.setItem(self.r, 0, newItem)
             self.r += 1

它正常工作,但我无法加载数字...... 只有字符串...... 奇怪的...

UPDATE2:

def add(self):
        for i in self.first:
             newItem = QtGui.QTableWidgetItem(str(i))
             self.tableWidget.setItem(self.r, 0, newItem)
             self.r += 1

但它将所有数字显示为浮点数....

UPDATE3:

def add(self):
        for i in self.first:
             try:
                newItem = QtGui.QTableWidgetItem(str(int(i)))
             except ValueError:
                newItem = QtGui.QTableWidgetItem(str(i))    
             self.tableWidget.setItem(self.r, 0, newItem)
             self.r += 1

问题解决了......

1 个答案:

答案 0 :(得分:1)

xlrd.open_wookbook需要文件名(字符串),而不是fname(文件对象)。

尝试:

        filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '/home', ".xls(*.xls)")
        wb = xlrd.open_workbook(filename)