How to save PyQt -TableWdiget-Tabular Data in Python main file or SQL DB?

元气小坏坏 提交于 2019-12-08 03:34:55

问题


I am a civil engineering student developing a python gui based tool for engineering calculation.Since all the calculations are based on table as we does in the excel file, I wanted to know how to save a table data entered through GUI tableWidget? And how to perform the operations on multiple tables?


回答1:


You can download xlsxwriter which is a python package for writing to ms excel. in this example, am using a push button which will be used to export the data from the table to ms excel. You should rename self.tableWidget to the name of your table in case you changed the default name.

self.exportButton.clicked.connect(self.exporter)

def exporter(self, filename=None):
    if not filename:
        filename = QtGui.QFileDialog.getSaveFileName(self, 'Save File'," "'.xlsx','(*.xlsx)')
    if filename:
        wb = xlsxwriter.Workbook(filename)
        self.sheetBook = wb.add_worksheet()
        self.export()
        wb.close()

def export(self):
    row = 0
    col = 0
    for i in range(self.tableWidget.columnCount()):
        for x in range(self.tableWidget.rowCount()):
            try:
                text = str(self.tableWidget.item(row, col).text())
                self.sheetBook.write(row, col, text)
                row += 1
            except AttributeError:
                row += 1
        row = 0
        col += 1


来源:https://stackoverflow.com/questions/48623964/how-to-save-pyqt-tablewdiget-tabular-data-in-python-main-file-or-sql-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!