qt如何将qtablewidget导出为 excel
时间: 2024-05-09 09:20:57 浏览: 156
QT中用QTableWdiget导出Excel表格
1. 导入pyqt5库和pandas库。
```python
import pandas as pd
from PyQt5.QtWidgets import QTableWidget
```
2. 创建一个QTableWidget对象并向其中添加数据。
```python
table = QTableWidget()
table.setRowCount(3)
table.setColumnCount(2)
table.setItem(0, 0, QTableWidgetItem("Alice"))
table.setItem(0, 1, QTableWidgetItem("25"))
table.setItem(1, 0, QTableWidgetItem("Bob"))
table.setItem(1, 1, QTableWidgetItem("30"))
table.setItem(2, 0, QTableWidgetItem("Charlie"))
table.setItem(2, 1, QTableWidgetItem("35"))
```
3. 将QTableWidget对象转换为pandas的DataFrame对象。
```python
data = []
header = []
for row in range(table.rowCount()):
row_data = []
for column in range(table.columnCount()):
item = table.item(row, column)
if item is not None:
row_data.append(item.text())
if row == 0:
header.append(item.text())
data.append(row_data)
df = pd.DataFrame(data, columns=header)
```
4. 将DataFrame对象导出为Excel文件。
```python
df.to_excel("table.xlsx", index=False)
```
完整代码示例:
```python
import pandas as pd
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem
# 创建QTableWidget并添加数据
table = QTableWidget()
table.setRowCount(3)
table.setColumnCount(2)
table.setItem(0, 0, QTableWidgetItem("Alice"))
table.setItem(0, 1, QTableWidgetItem("25"))
table.setItem(1, 0, QTableWidgetItem("Bob"))
table.setItem(1, 1, QTableWidgetItem("30"))
table.setItem(2, 0, QTableWidgetItem("Charlie"))
table.setItem(2, 1, QTableWidgetItem("35"))
# 将QTableWidget转换为DataFrame
data = []
header = []
for row in range(table.rowCount()):
row_data = []
for column in range(table.columnCount()):
item = table.item(row, column)
if item is not None:
row_data.append(item.text())
if row == 0:
header.append(item.text())
data.append(row_data)
df = pd.DataFrame(data, columns=header)
# 导出为Excel文件
df.to_excel("table.xlsx", index=False)
```
阅读全文