pyqt tablewidget导出excel
时间: 2023-09-08 15:00:54 浏览: 157
使用pyqt开发的GUI程序中要导出tablewidget中的数据到Excel,可以使用openpyxl库来实现。
首先,需要安装openpyxl库,可以使用pip install openpyxl进行安装。
导出Excel的步骤如下:
1. 导入所需的库和模块:
```python
from PyQt5.QtWidgets import QApplication, QTableWidget, QTableWidgetItem, QMainWindow
from openpyxl import Workbook
```
2. 创建一个QTableWidget并填充数据:
```python
table_widget = QTableWidget()
table_widget.setColumnCount(3)
table_widget.setRowCount(2)
table_widget.setItem(0, 0, QTableWidgetItem("A1"))
table_widget.setItem(0, 1, QTableWidgetItem("B1"))
table_widget.setItem(0, 2, QTableWidgetItem("C1"))
table_widget.setItem(1, 0, QTableWidgetItem("A2"))
table_widget.setItem(1, 1, QTableWidgetItem("B2"))
table_widget.setItem(1, 2, QTableWidgetItem("C2"))
```
3. 创建一个Workbook对象,并获取当前活动的sheet:
```python
wb = Workbook()
sheet = wb.active
```
4. 遍历tablewidget中的每个单元格,将其值写入到Excel中:
```python
for row in range(table_widget.rowCount()):
for col in range(table_widget.columnCount()):
value = table_widget.item(row, col).text()
sheet.cell(row=row+1, column=col+1).value = value
```
5. 保存Excel文件:
```python
wb.save("output.xlsx")
```
完整的代码如下:
```python
from PyQt5.QtWidgets import QApplication, QTableWidget, QTableWidgetItem, QMainWindow
from openpyxl import Workbook
app = QApplication([])
window = QMainWindow()
table_widget = QTableWidget()
table_widget.setColumnCount(3)
table_widget.setRowCount(2)
table_widget.setItem(0, 0, QTableWidgetItem("A1"))
table_widget.setItem(0, 1, QTableWidgetItem("B1"))
table_widget.setItem(0, 2, QTableWidgetItem("C1"))
table_widget.setItem(1, 0, QTableWidgetItem("A2"))
table_widget.setItem(1, 1, QTableWidgetItem("B2"))
table_widget.setItem(1, 2, QTableWidgetItem("C2"))
wb = Workbook()
sheet = wb.active
for row in range(table_widget.rowCount()):
for col in range(table_widget.columnCount()):
value = table_widget.item(row, col).text()
sheet.cell(row=row+1, column=col+1).value = value
wb.save("output.xlsx")
window.show()
app.exec_()
```
以上就是使用pyqt导出tablewidget数据到Excel的方法。最终生成的output.xlsx即为导出的Excel文件。
阅读全文