PyQt: QTableWidget to .xls file

Antoni4040 picture Antoni4040 · Aug 8, 2012 · Viewed 7.5k times · Source

So, I have a QTableWidget that I want to save it to an .xls file using the xlwt module...

Here's the code:

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

But that writes out only the text from cell 0,0 and nothing else...

I think that I have made some serious mistake...

Update:

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             

Solved the problem...

Answer

sid16rgt picture sid16rgt · Nov 18, 2012

You might also find it more concise and easier to use the output of the range (or xrange) as the indexes for your tableWidget.item call rather than worrying about incrementing your own counters. You might be using the sheet itself in other places in code, but if you're not, it would save you some memory to not assign the sheet to be an attribute variable of your class:

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

Because you are using the range command, the currentColumn variable will increment from 0 to columnCount() and currentRow will increment from 0 to currentRow()