So, I have an application with a QTableWidget and want to import an .xls file:
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
But, I get this error: TypeError: coercing to Unicode: need string or buffer, file found
What have I done wrong?
Update:
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
It's working, but I can't load numbers... Only strings... Weird...
Update2:
def add(self):
for i in self.first:
newItem = QtGui.QTableWidgetItem(str(i))
self.tableWidget.setItem(self.r, 0, newItem)
self.r += 1
But it displays all numbers as floats....
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
Problem solved...
xlrd.open_wookbook expects a filename (a string), not fname
(a file object).
Try:
filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '/home', ".xls(*.xls)")
wb = xlrd.open_workbook(filename)