Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

python - Export QTABLEWIDGET's data (Columns, rows , everything, ...) to SQLITE3

Export QTableWidgets Data populated by the user to the db file. (the db file doesn't exist so SQLITE3 will create it` in the cited Directory.)

Here's the code I used :

    self.CreateDatasetButton.connect(self.createDS)

def CreateDS(self):
    self.proceed = QtWidgets.QMessageBox.question(
        self, 
        'Information', 
        'Have you Verified your Data?',
        QtWidgets.QMessageBox.Yes|QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)
    if self.proceed == QtWidgets.QMessageBox.Yes:
        self.showDialog()
    else:
        pass

def showDialog(self):
    self.text, ok = QtWidgets.QInputDialog.getText(self, 'Almost Done !', 
        '

name your file :')
    if ok:
        self.Createdb()

def Createdb(self):
    conn = sqlite3.connect('__Datasets__/%s.db' %(self.text))
    # problema here
    conn.close()
    self.app_statusbar.showMessage('%s is created' %(self.text()))

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using pandas the task is simple, the solution is to convert the QTableWidget to a dataframe and then export it:

import sqlite3
import pandas as pd
from PyQt5 import QtWidgets


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        self.table_widget = QtWidgets.QTableWidget()
        self.create_data()
        button = QtWidgets.QPushButton("Export")
        button.clicked.connect(self.on_clicked)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.table_widget)
        lay.addWidget(button)

    def create_data(self):
        self.table_widget.setColumnCount(4)
        self.table_widget.setRowCount(10)
        self.table_widget.setHorizontalHeaderLabels(["A", "B", "C", "D"])

        import random
        for i in range(self.table_widget.rowCount()):
            for j in range(self.table_widget.columnCount()):
                it = QtWidgets.QTableWidgetItem(str(random.randint(0, 100)))
                self.table_widget.setItem(i, j, it)

    def on_clicked(self):
        proceed = QtWidgets.QMessageBox.question(self, 
            'Information', 
            'Have you Verified your Data?',
            QtWidgets.QMessageBox.Yes|QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)
        if proceed != QtWidgets.QMessageBox.Yes:
            return

        filename, ok = QtWidgets.QInputDialog.getText(self, 'Almost Done !', 'name your file :')
        if ok:
            self.saveToDb(filename, "table_name")

    def saveToDb(self, db_filename, tablename):
        d = {}
        for i in range(self.table_widget.columnCount()):
            l = []
            for j in range(self.table_widget.rowCount()):
                it = self.table_widget.item(j, i)
                l.append(it.text() if it is not None else "")
            h_item = self.table_widget.horizontalHeaderItem(i)
            n_column = str(i) if h_item is None else h_item.text()
            d[n_column] = l

        df = pd.DataFrame(data=d)
        engine = sqlite3.connect(db_filename)
        df.to_sql(tablename, con=engine)


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...