Python QtableWidget获取所有单元格的文本和数据框的标题

时间:2018-12-15 09:30:49

标签: python-3.x pandas dataframe pyqt5 qtablewidget

我想从Qtablewidget中获取所有单元格及其头部中的整个文本,并将其写入数据框(以便稍后将其导出到excel文件中)。该表可以用新的行,列和不同的标题进行编辑。我找到了this解决方案,该解决方案适用于数字,但适用于文本,程序会崩溃。

这是到目前为止我调整后的代码(简而言之,没有整个编辑选项):

import pandas as pd
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from pandas import DataFrame
import sys



data_single = {'hi': ['a', 'b'], 'hi2': ['d', 'c']}
tell_row=1

class TableWidget(QTableWidget):
    def __init__(self, df, parent=None):
        QTableWidget.__init__(self, parent)
        self.df = df
        nRows = len(self.df.index)
        nColumns = len(self.df.columns)
        self.setRowCount(nRows)
        self.setColumnCount(nColumns)

        for i in range(self.rowCount()):
            for j in range(self.columnCount()):
                x = self.df.iloc[i, j]
                self.setItem(i, j, QTableWidgetItem(x))

        self.cellChanged.connect(self.onCellChanged)

    #@pyqtSlot(int, int)
    def onCellChanged(self, row, column):
        text = self.item(row, column).text()
        number = float(text)
        self.df.set_value(row, column, number)


class App(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(700, 100, 350, 380)
        df_rows = tell_row
        df_cols = 1
        df =pd.DataFrame(data_single)
        self.tableWidget = TableWidget(df, self)

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.tableWidget)
        self.button = QPushButton('Print DataFrame', self)
        self.layout.addWidget(self.button)
        self.setLayout(self.layout)
        self.button.clicked.connect(self.print_my_df)

    @pyqtSlot()
    def print_my_df(self):
        some_df =self.tableWidget.df
        print(some_df)

        fn, _ = QFileDialog.getSaveFileName(self, 'Speichern unter', None, 'Excel Dateien (.xlsx);;Alle Dateien()')
        if fn != '':
            if QFileInfo(fn).suffix() == "": fn += '.xlsx'
        df = DataFrame(some_df)
        df.to_excel(fn, sheet_name='Ergebnisse', index=False)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    ex.show()
    sys.exit(app.exec_())

0 个答案:

没有答案