Python+PyQt 实现将数据导出为文件保存在本地
Posted 稚皓君
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python+PyQt 实现将数据导出为文件保存在本地相关的知识,希望对你有一定的参考价值。
Python+PyQt 实现将数据导出为文件保存在本地
实现效果
实现代码
import openpyxl
import sys
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem, QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QFileDialog, QMessageBox
from PyQt5 import QtCore
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("导出文件测试")
self.tableWidget = QTableWidget()
self.tableWidget.setRowCount(3)
self.tableWidget.setColumnCount(2)
self.tableWidget.setHorizontalHeaderLabels(["Name", "Age"])
self.tableWidget.setItem(0, 0, QTableWidgetItem("Tom"))
self.tableWidget.setItem(0, 1, QTableWidgetItem("20"))
self.tableWidget.setItem(1, 0, QTableWidgetItem("Jack"))
self.tableWidget.setItem(1, 1, QTableWidgetItem("25"))
self.tableWidget.setItem(2, 0, QTableWidgetItem("Lucy"))
self.tableWidget.setItem(2, 1, QTableWidgetItem("30"))
self.saveButton = QPushButton("保存")
self.saveButton.clicked.connect(self.save_excel)
layout = QVBoxLayout()
layout.addWidget(self.tableWidget)
layout.addWidget(self.saveButton)
centralWidget = QWidget()
centralWidget.setLayout(layout)
self.setCentralWidget(centralWidget)
def save_excel(self):
filename, _ = QFileDialog.getSaveFileName(self, "Save file", "", "Excel files (*.xlsx)")
if filename:
workbook = openpyxl.Workbook()
worksheet = workbook.active
# 保存表头
for column in range(self.tableWidget.columnCount()):
header = self.tableWidget.horizontalHeaderItem(column)
worksheet.cell(row=1, column=column+1, value=str(header.text()))
# 保存数据
for row in range(self.tableWidget.rowCount()):
for column in range(self.tableWidget.columnCount()):
item = self.tableWidget.item(row, column)
if item is not None:
worksheet.cell(row=row+2, column=column+1, value=str(item.text()))
workbook.save(filename)
QMessageBox.information(self, "提示", "数据文件保存成功!", QMessageBox.Ok)
if __name__ == "__main__":
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
温馨提示
需要导包,不然会报错
以上是关于Python+PyQt 实现将数据导出为文件保存在本地的主要内容,如果未能解决你的问题,请参考以下文章
将 qtDesigner .ui 文件链接到 python/pyqt?