Dec-15-2018, 03:43 PM
I would like to get the whole text in all cells and its headears from a Qtablewidget and write it to an dataframe (to export it later to an excel file). The table can be edited with new rows, columns and different headers. I found this solution,which works fine with numbers but with text the programm collapses.
The code is in python 3.6 and pyqt5.
Here is my adjusted code (in short without the whole editing options) so far:
The code is in python 3.6 and pyqt5.
Here is my adjusted code (in short without the whole editing options) so far:
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_())