python pyqt5编写一个界面,能够导入excel数据,并对数据进行增删改查,高级
时间: 2024-02-13 12:03:49 浏览: 151
QT+mysql.zip_MYSQL_QT图书_qt mysql_qt 增删改查_qt 界面
好的,我可以为您提供一份 Pyqt5 编写的 Excel 数据管理界面的代码,它可以实现导入 Excel 数据、增删改查和高级操作。请注意,以下代码仅供参考,您可以根据自己的需求进行修改和优化。
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox, QTableWidgetItem
import openpyxl
class ExcelManager(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('Excel数据管理')
self.setGeometry(100, 100, 800, 600)
self.tableWidget = QTableWidget(self)
self.tableWidget.setGeometry(10, 10, 780, 520)
menubar = self.menuBar()
fileMenu = menubar.addMenu('文件')
importAction = fileMenu.addAction('导入')
importAction.triggered.connect(self.importExcel)
editMenu = menubar.addMenu('编辑')
addAction = editMenu.addAction('新增')
addAction.triggered.connect(self.addRow)
deleteAction = editMenu.addAction('删除')
deleteAction.triggered.connect(self.deleteRow)
modifyAction = editMenu.addAction('修改')
modifyAction.triggered.connect(self.modifyRow)
searchMenu = menubar.addMenu('查询')
simpleSearchAction = searchMenu.addAction('简单查询')
simpleSearchAction.triggered.connect(self.simpleSearch)
advancedSearchAction = searchMenu.addAction('高级查询')
advancedSearchAction.triggered.connect(self.advancedSearch)
def importExcel(self):
filePath, _ = QFileDialog.getOpenFileName(self, '选择文件', '', 'Excel文件 (*.xlsx)')
if filePath:
try:
workbook = openpyxl.load_workbook(filePath)
sheet = workbook.active
self.tableWidget.setRowCount(sheet.max_row)
self.tableWidget.setColumnCount(sheet.max_column)
for i in range(1, sheet.max_row + 1):
for j in range(1, sheet.max_column + 1):
cell = sheet.cell(row=i, column=j)
item = QTableWidgetItem(str(cell.value))
self.tableWidget.setItem(i - 1, j - 1, item)
self.tableWidget.setHorizontalHeaderLabels([sheet.cell(row=1, column=j).value for j in range(1, sheet.max_column + 1)])
except Exception as e:
QMessageBox.critical(self, '错误', str(e))
def addRow(self):
rowPosition = self.tableWidget.rowCount()
self.tableWidget.insertRow(rowPosition)
def deleteRow(self):
selectedRows = set()
for item in self.tableWidget.selectedItems():
selectedRows.add(item.row())
for i in reversed(sorted(selectedRows)):
self.tableWidget.removeRow(i)
def modifyRow(self):
selectedItems = self.tableWidget.selectedItems()
if len(selectedItems) != self.tableWidget.columnCount():
QMessageBox.warning(self, '警告', '请选中一整行进行修改!')
return
row = selectedItems[0].row()
items = []
for i in range(self.tableWidget.columnCount()):
item = self.tableWidget.item(row, i)
items.append(item.text() if item else '')
newItems, ok = ModifyDialog.modify(items)
if ok:
for i in range(self.tableWidget.columnCount()):
item = QTableWidgetItem(newItems[i])
self.tableWidget.setItem(row, i, item)
def simpleSearch(self):
searchText, ok = SearchDialog.search()
if ok:
for i in range(self.tableWidget.rowCount()):
for j in range(self.tableWidget.columnCount()):
item = self.tableWidget.item(i, j)
if item and searchText in item.text():
self.tableWidget.selectRow(i)
break
def advancedSearch(self):
searchConditions, ok = SearchDialog.advancedSearch()
if ok:
for i in range(self.tableWidget.rowCount()):
matched = True
for condition in searchConditions:
col, op, value = condition
item = self.tableWidget.item(i, col)
if not item:
matched = False
break
itemText = item.text()
if op == '=' and itemText != value:
matched = False
break
elif op == 'like' and value not in itemText:
matched = False
break
elif op == '>' and float(itemText) <= float(value):
matched = False
break
elif op == '>=' and float(itemText) < float(value):
matched = False
break
elif op == '<' and float(itemText) >= float(value):
matched = False
break
elif op == '<=' and float(itemText) > float(value):
matched = False
break
if matched:
self.tableWidget.selectRow(i)
class ModifyDialog(QMainWindow):
def __init__(self, items):
super().__init__()
self.items = items
self.initUI()
def initUI(self):
self.setWindowTitle('修改')
self.setGeometry(300, 300, 400, 300)
label1 = QLabel('第1列:', self)
label1.move(10, 10)
self.lineEdit1 = QLineEdit(self)
self.lineEdit1.move(100, 10)
self.lineEdit1.setText(self.items[0])
label2 = QLabel('第2列:', self)
label2.move(10, 50)
self.lineEdit2 = QLineEdit(self)
self.lineEdit2.move(100, 50)
self.lineEdit2.setText(self.items[1])
label3 = QLabel('第3列:', self)
label3.move(10, 90)
self.lineEdit3 = QLineEdit(self)
self.lineEdit3.move(100, 90)
self.lineEdit3.setText(self.items[2])
label4 = QLabel('第4列:', self)
label4.move(10, 130)
self.lineEdit4 = QLineEdit(self)
self.lineEdit4.move(100, 130)
self.lineEdit4.setText(self.items[3])
label5 = QLabel('第5列:', self)
label5.move(10, 170)
self.lineEdit5 = QLineEdit(self)
self.lineEdit5.move(100, 170)
self.lineEdit5.setText(self.items[4])
okButton = QPushButton('确定', self)
okButton.move(100, 220)
okButton.clicked.connect(self.accept)
cancelButton = QPushButton('取消', self)
cancelButton.move(200, 220)
cancelButton.clicked.connect(self.reject)
@staticmethod
def modify(items):
dialog = ModifyDialog(items)
result = dialog.exec_()
newItems = [dialog.lineEdit1.text(), dialog.lineEdit2.text(), dialog.lineEdit3.text(), dialog.lineEdit4.text(), dialog.lineEdit5.text()]
return newItems, result == QDialog.Accepted
class SearchDialog(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('查询')
self.setGeometry(300, 300, 300, 200)
self.lineEdit = QLineEdit(self)
self.lineEdit.setGeometry(10, 10, 200, 30)
self.lineEdit.returnPressed.connect(self.accept)
okButton = QPushButton('确定', self)
okButton.setGeometry(10, 60, 80, 30)
okButton.clicked.connect(self.accept)
cancelButton = QPushButton('取消', self)
cancelButton.setGeometry(100, 60, 80, 30)
cancelButton.clicked.connect(self.reject)
@staticmethod
def search():
dialog = SearchDialog()
result = dialog.exec_()
return dialog.lineEdit.text(), result == QDialog.Accepted
@staticmethod
def advancedSearch():
dialog = AdvancedSearchDialog()
result = dialog.exec_()
return dialog.getSearchConditions(), result == QDialog.Accepted
class AdvancedSearchDialog(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('高级查询')
self.setGeometry(300, 300, 400, 300)
self.tableWidget = QTableWidget(self)
self.tableWidget.setGeometry(10, 10, 380, 200)
self.tableWidget.setColumnCount(3)
self.tableWidget.setHorizontalHeaderLabels(['列', '操作符', '值'])
self.tableWidget.verticalHeader().setVisible(False)
okButton = QPushButton('确定', self)
okButton.move(100, 220)
okButton.clicked.connect(self.accept)
cancelButton = QPushButton('取消', self)
cancelButton.move(200, 220)
cancelButton.clicked.connect(self.reject)
def getSearchConditions(self):
searchConditions = []
for i in range(self.tableWidget.rowCount()):
col = self.tableWidget.item(i, 0).text()
op = self.tableWidget.item(i, 1).text()
value = self.tableWidget.item(i, 2).text()
searchConditions.append((int(col), op, value))
return searchConditions
def addCondition(self):
rowPosition = self.tableWidget.rowCount()
self.tableWidget.insertRow(rowPosition)
def deleteCondition(self):
selectedRows = set()
for item in self.tableWidget.selectedItems():
selectedRows.add(item.row())
for i in reversed(sorted(selectedRows)):
self.tableWidget.removeRow(i)
if __name__ == '__main__':
app = QApplication(sys.argv)
excelManager = ExcelManager()
excelManager.show()
sys.exit(app.exec_())
```
这份代码实现了一个 Excel 数据管理界面,包括导入 Excel 数据、增删改查和高级操作。您可以通过菜单栏进行操作,具体实现方式请参考代码注释。如果您有任何问题或需要进一步优化,请随时与我联系。
阅读全文