如何使用 Pandas 将 QTableWidget 数据导出到 Excel?
How to export QTableWidget data to Excel using Pandas?
我正在尝试将数据从 QTableWidget 传递到 Excel。为什么在Excel中只写了table的最后一行? (在打印中,显示了完整的 table)。
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)
您需要创建一个列表列表来保存所有行:
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)
我正在尝试将数据从 QTableWidget 传递到 Excel。为什么在Excel中只写了table的最后一行? (在打印中,显示了完整的 table)。
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)
您需要创建一个列表列表来保存所有行:
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)