所以,我有一个带有 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
它正在工作,但我无法加载数字......只有字符串......奇怪......
更新2:
def add(self):
for i in self.first:
newItem = QtGui.QTableWidgetItem(str(i))
self.tableWidget.setItem(self.r, 0, newItem)
self.r += 1
但它将所有数字显示为浮点数....
更新3:
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
问题解决了...