import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox, QFileDialog
from openpyxl import load_workbook
class ExcelReaderApp(QWidget):
def __init__(self):
super().__init__()
self.file_path = None # 用于保存选定的Excel文件路径
self.init_ui()
def init_ui(self):
layout = QVBoxLayout()
self.label = QLabel('请输入关键字:') # 创建标签
self.keyword_input = QLineEdit() # 创建文本输入框
self.search_button = QPushButton('搜索') # 创建按钮
self.search_button.clicked.connect(self.search_in_excel) # 按钮点击事件绑定到搜索函数
layout.addWidget(self.label) # 将标签添加到布局
layout.addWidget(self.keyword_input) # 将文本输入框添加到布局
layout.addWidget(self.search_button) # 将按钮添加到布局
self.setLayout(layout) # 设置窗口布局
self.setGeometry(300, 300, 300, 150) # 设置窗口大小和位置
self.setWindowTitle('Excel Reader') # 设置窗口标题
self.choose_file() # 在初始化时调用文件选择方法
def choose_file(self):
# 创建文件选择对话框
file_dialog = QFileDialog()
file_dialog.setNameFilter('Excel Files (*.xlsx *.xls)')
file_dialog.setWindowTitle('选择Excel文件')
file_dialog.setFileMode(QFileDialog.ExistingFile)
# 打开文件选择对话框
if file_dialog.exec_():
selected_files = file_dialog.selectedFiles()
self.file_path = selected_files[0]
QMessageBox.information(self, '文件已选定', f'已选定文件: {self.file_path}')
def search_in_excel(self):
keyword = self.keyword_input.text() # 获取用户输入的关键字
if not keyword:
QMessageBox.warning(self, '警告', '请输入关键字') # 如果关键字为空,显示警告
return
if not self.file_path:
QMessageBox.warning(self, '警告', '请先选择Excel文件') # 如果未选择Excel文件,显示警告
return
try:
# 读取选定的Excel文件
workbook = load_workbook(self.file_path)
sheet = workbook.active
found = False
# 遍历Excel表格中的每一行,从第二行开始(假设第一行是标题行)
for row in sheet.iter_rows(min_row=2, values_only=True):
if keyword in row:
found = True
result = f'关键字"{keyword}"对应的信息为: {row}'
QMessageBox.information(self, '搜索结果', result)
break
if not found:
QMessageBox.information(self, '搜索结果', f'未找到关键字"{keyword}"对应的信息')
except Exception as e:
QMessageBox.critical(self, '错误', f'发生错误: {str(e)}')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = ExcelReaderApp()
ex.show()
sys.exit(app.exec_())
pyqt5 选择EXCEL并读取内容,根据输入的关键字查找到相应的信息
于 2023-12-13 10:45:24 首次发布