qt中的表格数据如何导出到excel中
时间: 2023-06-04 10:04:00 浏览: 259
您可以使用QTableWidget的数据转换功能将表格数据转换为QAbstractItemModel对象,并使用QXlsx将其导出到Excel文件中。具体代码如下:
```python
import sys
from PyQt5.QtWidgets import QApplication, QTableWidget, QTableWidgetItem
from PyQt5.QtGui import QStandardItemModel
from PyQt5.QtCore import QAbstractItemModel
from PyQt5.QtXlsx import QXlsx
def exportToExcel(table):
model = table.model()
rows = model.rowCount()
cols = model.columnCount()
xlsx = QXlsx()
for row in range(rows):
for col in range(cols):
item = model.item(row, col)
if item is not None:
xlsx.write(row+1, col+1, item.text())
xlsx.saveAs("table.xlsx")
if __name__ == "__main__":
app = QApplication(sys.argv)
table = QTableWidget()
table.setRowCount(2)
table.setColumnCount(2)
table.setItem(0, 0, QTableWidgetItem("John"))
table.setItem(0, 1, QTableWidgetItem("Doe"))
table.setItem(1, 0, QTableWidgetItem("Jane"))
table.setItem(1, 1, QTableWidgetItem("Doe"))
table.show()
exportToExcel(table)
sys.exit(app.exec_())
```
此代码将一个2x2的表格数据导出为Excel文件。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)