Home > Net >  How to export QTableWidget data to Excel using Pandas?
How to export QTableWidget data to Excel using Pandas?

Time:05-24

I'm trying to pass data from a QTableWidget to Excel. Why in Excel is only the last row of the table written? (In print, the complete table is shown).

rowCount = self.QTableWidget.rowCount()
columnCount = 5

for row in range(rowCount):
    rowData = []
    for column in range(columnCount):
        widgetItem = self.QTableWidget.item(row, column)
        if widgetItem and widgetItem.text:
            rowData.append(widgetItem.text())
        else:
            rowData.append('NULL')
    print(rowData)

df = pd.DataFrame(columns=rowData)
df.to_excel('Table.xlsx', index=False)

CodePudding user response:

You need to create a list of lists to hold all the rows:

rowCount = self.QTableWidget.rowCount()
columnCount = 5

# add this line
data = []

for row in range(rowCount):
    rowData = []
    for column in range(columnCount):
        widgetItem = self.QTableWidget.item(row, column)
        if widgetItem and widgetItem.text:
            rowData.append(widgetItem.text())
        else:
            rowData.append('NULL')
    print(rowData)

    # add this line
    data.append(rowData)

# change these two lines
df = pd.DataFrame(data)
df.to_excel('Table.xlsx', header=False, index=False)
  • Related