所以,我有一个QTableWidget,我想用xlwt模块将它保存到.xls文件...
以下是代码:
def savefile(self):
filename = unicode(QtGui.QFileDialog.getSaveFileName(self, 'Save File', '', ".xls(*.xls)"))
wbk = xlwt.Workbook()
self.sheet = wbk.add_sheet("sheet")
self.row = 0
self.col = 0
self.add2(self.row, self.col)
wbk.save(filename)
def add2(self, row, col):
for i in range(self.tableWidget.columnCount()):
for x in range(self.tableWidget.rowCount()):
try:
teext = str(self.tableWidget.item(row, col).text())
self.sheet.write(row, col, teext)
row += 1
except AttributeError:
pass
col += 1
但是,它只写出来自单元格0,0的文本,而没有其他内容......
我认为我犯了一些严重的错误......
更新
def savefile(self):
filename = unicode(QtGui.QFileDialog.getSaveFileName(self, 'Save File', '', ".xls(*.xls)"))
wbk = xlwt.Workbook()
self.sheet = wbk.add_sheet("sheet", cell_overwrite_ok=True)
self.add2()
wbk.save(filename)
def add2(self):
row = 0
col = 0
for i in range(self.tableWidget.columnCount()):
for x in range(self.tableWidget.rowCount()):
try:
teext = str(self.tableWidget.item(row, col).text())
self.sheet.write(row, col, teext)
row += 1
except AttributeError:
row += 1
row = 0
col += 1
解决了问题...
答案 0 :(得分:1)
您可能还会发现使用范围(或xrange)的输出作为tableWidget.item调用的索引更简洁,更容易,而不是担心增加自己的计数器。您可能在代码中的其他位置使用工作表本身,但如果不是,则会节省一些内存,以便不将工作表指定为您的类的属性变量:
def savefile(self):
filename = unicode(QtGui.QFileDialog.getSaveFileName(self, 'Save File', '', ".xls(*.xls)"))
wbk = xlwt.Workbook()
sheet = wbk.add_sheet("sheet", cell_overwrite_ok=True)
self.add2(sheet)
wbk.save(filename)
def add2(self, sheet):
for currentColumn in range(self.tableWidget.columnCount()):
for currentRow in range(self.tableWidget.rowCount()):
try:
teext = str(self.tableWidget.item(currentRow, currentColumn).text()
sheet.write(currentRow, currentColumn, teext)
except AttributeError:
pass
因为您正在使用range命令,所以currentColumn变量将从0递增到columnCount(),currentRow将从0递增到currentRow()