[Windows]_Excel文件批量加密工具(开源)

资源介绍:

import os
import sys
import win32com.client as win32
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
                             QHBoxLayout, QLabel, QLineEdit, QPushButton,
                             QTextEdit, QFileDialog, QProgressBar, QMessageBox,
                             QCheckBox)
from PyQt5.QtCore import Qt, QThread, pyqtSignal
  
  
class EncryptionWorker(QThread):
    """加密工作线程"""
    progress_update = pyqtSignal(str)
    progress_value = pyqtSignal(int)
    finished_signal = pyqtSignal(int, int)
  
    def __init__(self, directory, password, suffix):
        super().__init__()
        self.directory = directory
        self.password = password
        self.suffix = suffix
  
    def run(self):
        """执行加密操作"""
        # 支持的Excel文件扩展名
        excel_extensions = ['.et', '.xls', '.xlsx']
  
        # 确保目录路径存在
        if not os.path.exists(self.directory):
            self.progress_update.emit(f"错误: 目录 '{self.directory}' 不存在!")
            return
  
        # 计数器
        encrypted_files = []
        failed_files = []
  
        self.progress_update.emit(f"开始扫描目录: {self.directory}")
  
        # 首先计算总文件数
        excel_files = []
        for root, _, files in os.walk(self.directory):
            for file in files:
                file_path = os.path.join(root, file)
                file_ext = os.path.splitext(file)[1].lower()
                if file_ext in excel_extensions:
                    excel_files.append(file_path)
  
        total_files = len(excel_files)
        self.progress_update.emit(f"找到 {total_files} 个Excel文件")
  
        # 初始化Excel应用程序
        excel = None
        try:
            excel = win32.gencache.EnsureDispatch('Excel.Application')
            excel.DisplayAlerts = False
  
            # 遍历处理所有文件
            for index, file_path in enumerate(excel_files):
                try:
                    self.progress_update.emit(f"正在处理: {file_path}")
                    self.progress_value.emit(int((index / total_files) * 100) if total_files > 0 else 0)
  
                    # 生成新文件名
                    file_dir = os.path.dirname(file_path)
                    file_name, file_ext = os.path.splitext(os.path.basename(file_path))
                    new_file_name = f"{file_name}{self.suffix}{file_ext}"
                    new_file_path = os.path.join(file_dir, new_file_name)
  
                    # 打开Excel文件
                    wb = excel.Workbooks.Open(os.path.abspath(file_path))
  
                    # 设置密码并另存为新文件
                    wb.SaveAs(os.path.abspath(new_file_path), Password=self.password)
                    wb.Close()
  
                    encrypted_files.append(new_file_path)
                    self.progress_update.emit(f"已加密并保存为: {new_file_path}")
                except Exception as e:
                    failed_files.append((file_path, str(e)))
                    self.progress_update.emit(f"加密失败: {file_path} - 错误: {str(e)}")
        except Exception as e:
            self.progress_update.emit(f"初始化Excel应用程序失败: {str(e)}")
        finally:
            # 确保Excel应用程序被关闭
            if excel:
                try:
                    excel.Quit()
                except:
                    pass
  
        self.progress_value.emit(100)
        self.finished_signal.emit(len(encrypted_files), len(failed_files))
  
  
class ExcelEncryptorApp(QMainWindow):
    """Excel文件批量加密工具主窗口"""
  
    def __init__(self):
        super().__init__()
        self.init_ui()
  
    def init_ui(self):
        """初始化用户界面"""
        # 设置窗口标题和大小
        self.setWindowTitle('Excel文件批量加密工具----吾爱破解----By:墨羽风')
        self.setGeometry(300, 300, 600, 500)
  
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
  
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
  
        # 目录选择部分
        dir_layout = QHBoxLayout()
        dir_label = QLabel('目录路径:')
        self.dir_edit = QLineEdit()
        browse_btn = QPushButton('浏览...')
        browse_btn.clicked.connect(self.browse_directory)
  
        dir_layout.addWidget(dir_label)
        dir_layout.addWidget(self.dir_edit)
        dir_layout.addWidget(browse_btn)
  
        # 密码输入部分
        pwd_layout = QHBoxLayout()
        pwd_label = QLabel('加密密码:')
        self.pwd_edit = QLineEdit()
        self.pwd_edit.setEchoMode(QLineEdit.Password)
  
        pwd_layout.addWidget(pwd_label)
        pwd_layout.addWidget(self.pwd_edit)
  
        # 文件后缀输入部分
        suffix_layout = QHBoxLayout()
        suffix_label = QLabel('文件后缀:')
        self.suffix_edit = QLineEdit()
        self.suffix_edit.setText("_加密")
  
        suffix_layout.addWidget(suffix_label)
        suffix_layout.addWidget(self.suffix_edit)
  
        # 操作按钮
        btn_layout = QHBoxLayout()
        self.encrypt_btn = QPushButton('开始加密')
        self.encrypt_btn.clicked.connect(self.start_encryption)
  
        btn_layout.addStretch()
        btn_layout.addWidget(self.encrypt_btn)
  
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setValue(0)
  
        # 日志输出区域
        log_label = QLabel('处理日志:')
        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
  
        # 添加所有部件到主布局
        main_layout.addLayout(dir_layout)
        main_layout.addLayout(pwd_layout)
        main_layout.addLayout(suffix_layout)
        main_layout.addLayout(btn_layout)
        main_layout.addWidget(self.progress_bar)
        main_layout.addWidget(log_label)
        main_layout.addWidget(self.log_text)
  
    def browse_directory(self):
        """打开目录选择对话框"""
        directory = QFileDialog.getExistingDirectory(self, '选择目录')
        if directory:
            self.dir_edit.setText(directory)
  
    def start_encryption(self):
        """开始加密操作"""
        directory = self.dir_edit.text().strip()
        password = self.pwd_edit.text().strip()
        suffix = self.suffix_edit.text().strip()
  
        # 验证输入
        if not directory:
            QMessageBox.warning(self, '输入错误', '请选择要处理的目录')
            return
  
        if not password:
            QMessageBox.warning(self, '输入错误', '请输入加密密码')
            return
  
        if not suffix:
            reply = QMessageBox.question(self, '确认操作',
                                         '您没有输入文件后缀,加密后的文件将覆盖原文件,是否继续?',
                                         QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if reply == QMessageBox.No:
                return
  
        # 确认操作
        reply = QMessageBox.question(self, '确认操作',
                                     f'将对目录 "{directory}" 中的所有Excel文件进行加密,并保存为带有后缀 "{suffix}" 的新文件,是否继续?',
                                     QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
  
        if reply == QMessageBox.Yes:
            # 清空日志和进度条
            self.log_text.clear()
            self.progress_bar.setValue(0)
  
            # 禁用按钮,防止重复操作
            self.encrypt_btn.setEnabled(False)
  
            # 创建并启动工作线程
            self.worker = EncryptionWorker(directory, password, suffix)
            self.worker.progress_update.connect(self.update_log)
            self.worker.progress_value.connect(self.progress_bar.setValue)
            self.worker.finished_signal.connect(self.encryption_finished)
            self.worker.start()
  
    def update_log(self, message):
        """更新日志输出"""
        self.log_text.append(message)
        # 自动滚动到底部
        self.log_text.verticalScrollBar().setValue(
            self.log_text.verticalScrollBar().maximum()
        )
  
    def encryption_finished(self, encrypted, failed):
        """加密完成后的处理"""
        self.update_log(f"\n加密完成! 成功加密 {encrypted} 个文件,失败 {failed} 个文件。")
        self.encrypt_btn.setEnabled(True)
  
        # 显示完成消息
        QMessageBox.information(self, '操作完成',
                                f'加密完成!\n成功加密 {encrypted} 个文件\n失败 {failed} 个文件')
  
  
def main():
    """程序入口点"""
    app = QApplication(sys.argv)
    window = ExcelEncryptorApp()
    window.show()
    sys.exit(app.exec_())
  
  
if __name__ == "__main__":
    main()

 

资源截图:

下载地址:

download
来源:默认下载 | 提取码:溯光笔记整理

download
来源:诚通云盘 | 提取码:溯光笔记整理

此处内容需要回复后并刷新才能查看

此处内容需要回复后并刷新才能查看

THE END