Umutins62
Umutins62

Reputation: 23

Python PyQt5 qtableWidget to excel eror

Traceback (most recent call last):
  File "C:\Users\umutcelik\Desktop\Debi\DebiHesabi.py", line 181, in exportToExcel
    df.at[row, columnHeaders[col]] = self.tableWidget.item(row, col).text()
AttributeError: 'NoneType' object has no attribute 'text'
PS C:\Users\umutcelik\Desktop\Debi>`

When I run the method below, I get the error above. What is the problem? Thanks.

def exportToExcel(self):
        wb = openpyxl.Workbook()
        columnHeaders = []

        # create column header list
        for j in range(self.tableWidget.columnCount()):
            columnHeaders.append(self.tableWidget.horizontalHeaderItem(j).text())

        df = pd.DataFrame(columns=columnHeaders)
        print(df)

        # create dataframe object recordset
        for row in range(self.tableWidget.rowCount()):
            for col in range(self.tableWidget.columnCount()):
                df.at[row, columnHeaders[col]] = self.tableWidget.item(row, col).text()

        df.to_excel('deneme.xlsx', index=False)
        os.system("deneme.xlsx")`

Upvotes: 0

Views: 280

Answers (1)

eyllanesc
eyllanesc

Reputation: 244132

Not every cell has a QTableWidgetItem associated with it so you should check that it is not None:

for row in range(self.tableWidget.rowCount()):
    for col in range(self.tableWidget.columnCount()):
        item = self.tableWidget.item(row, col)
        df.at[row, columnHeaders[col]] = item.text() if item is not None else ""

Upvotes: 1

Related Questions