问题
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