Search code examples
pythonexcelpyqt5openpyxlqtablewidget

how to save qtablewidget data into excel file using openpyxl


I have a qtablewidet that has data and when the user clicks the export button a dialog will appear asking for filename to save as excel, how do i do that using openpyxl?

here is my code

self.exportbtn.clicked.connect(self.export)

    def export(self):
        try:
            filename = QtWidgets.QFileDialog.getSaveFileName(self, 'Save file', '','Excel files(*.xlsx)')
            wb = Workbook()
            sheet = wb.active
            for column in range(self.tableWidget.columnCount()):
                for row in range(self.tableWidget.rowCount()):
                    try:
                        text = str(self.tableWidget.item(row, column).text())
                        sheet.write(row, column, text)
                        wb.save(filename)
                    except Exception as e:
                        print("Error Writing file.")
        except Exception as e:
            print("Error Saving file.")

when i try to click save from the dialog, the output right now is this

enter image description here

how do i save the whole data including the headers from qtablewidget to an excel file using openpyxl?

update: i edited my code now and i am able to create the file but the data from the qtablewidget is still not written in the excel file

def export(self):
        filename, filter = QtWidgets.QFileDialog.getSaveFileName(self, 'Save file', '','Excel files (*.xlsx)')
        wb = Workbook()
        sheet = wb.active
        if not filename:
            for column in range(self.tableWidget.columnCount()):
                for row in range(self.tableWidget.rowCount()):
                    try:
                        text = str(self.tableWidget.item(row, column).text())
                        sheet.write(row, column, text)                    
                    except AttributeError:
                        pass
        wb.save(filename)

i tried printing the data from the qtablewidget and it shows, it just doesn't save in the excel file, is there still something missing?


Solution

  • So your line wb.save(filename) is inside your for loop, thereby the same filename is being saved on every loop.

    Move that line outside and after the for loops at the outer indentation and therefore save it only once.

    Also, ensure that the filename does not already exist, else you may get a pop dialog "Are you sure?" and you then need to force save it.