python win32com加密表格文件;加密目录下的所有表格文件

需求背景:写一个工具,对指定路径下的所有Excel文件进行加密,设置打开密码和编辑密码

实现思路:需要用python遍历指定目录下的所有文件,判断是否是EXCEl文件,还要判断文件是否原本就有密码,加密完成后将结果写入到文本文件

代码:

import os
import tkinter
import tkinter.filedialog
from tkinter import Tk, LabelFrame, Label, Entry, Button, END, messagebox
import win32com.client
import win32com
import pandas as pd
import xlrd

root = Tk()
root.title("python小工具")
root.wm_geometry('500x280+500+250')
root.resizable(False, False)

l_frame_1 = LabelFrame(root, text="表格批量加密", padx=10, pady=10)
l_frame_1.pack(pady=20)

label_1 = Label(l_frame_1, text="请选择待加密表格文件所在路径:")
text_box = Entry(l_frame_1, bd=2)

label_1.grid(row=0, column=0, padx=5, pady=10)
text_box.grid(row=0, column=1, padx=5, pady=10)


def btn_view_click():
    text_box.delete(0, END)
    text_box.insert(0, tkinter.filedialog.askdirectory())


btn_view = Button(l_frame_1, text='浏览...', command=btn_view_click)
btn_view.grid(row=0, column=2, padx=5, pady=10)

label_open_pwd = Label(l_frame_1, text="设置文档打开密码:")
label_edit_pwd = Label(l_frame_1, text='设置文档编辑密码:')
entry_open_pwd = Entry(l_frame_1, bd=2)
entry_edit_pwd = Entry(l_frame_1, bd=2)
label_open_pwd.grid(row=1, column=0, padx=10, pady=10)
label_edit_pwd.grid(row=2, column=0, padx=10, pady=10)
entry_open_pwd.grid(row=1, column=1, padx=10, pady=10)
entry_edit_pwd.grid(row=2, column=1, padx=0, pady=10)


def btn_encrypt_click():
    file_path = text_box.get()
    open_pwd = entry_open_pwd.get()
    edit_pwd = entry_edit_pwd.get()
    success_list = []
    failed_list = []

    if file_path != "":
        # 遍历路径下的所有文件、文件夹
        for dir_path, dir_names, file_names in os.walk(file_path):
            for filename in file_names:
                # 根据文件后缀名判断是否表格文件,并排除~$开头的临时文件
                if (not filename.startswith("~$")) and (filename.endswith(".xls") or filename.endswith(".xlsx")):
                    full_path = os.path.join(dir_path, filename).replace("/", "\\")
                    try:
                        # 先使用pandas读取一遍,有密码的会打不开报错,先排除掉
                        # 此处用win32com来试着打开的话,有密码的文件不会报错,而是弹出密码提示框,所以不能用win32com来判断有没有密码
                        df = pd.read_excel(full_path,sheet_name=0,index_col=0,header=None)
                        try:
                            # pandas能读取说明没密码
                            del df
                            xcl = win32com.client.Dispatch("Excel.Application")
                            xcl.DisplayAlerts = False  # 不显示警告,保存文件时直接覆盖保存,不弹出提示
                            xcl.Visible = False  # 后台运行
                            wb = xcl.Workbooks.Open(full_path)
                            wb.SaveAs(full_path, None, open_pwd, edit_pwd)
                            xcl.Quit()
                            if len(success_list) < 100 :
                                success_list.append(full_path)
                        except Exception as e:
                            if len(failed_list) < 100:
                                failed_list.append(full_path + ";错误原因:" + e)
                    except xlrd.biffh.XLRDError as e: # 文档有密码时报的错
                        if len(failed_list) < 100:
                            failed_list.append(full_path + ";错误原因:文档本身已有密码")

        # 执行完毕后,将执行结果写到文本文件里面
        s = "\n"
        log_file = open('表格加密日志.txt', 'w')
        log_file.write("已成功加密的清单如下:\n")
        log_file.write(s.join(success_list))
        log_file.write("\n")
        log_file.write("加密失败的清单如下:\n")
        if failed_list:
            log_file.write(s.join(failed_list))
        else:
            log_file.write("不存在加密失败的文件")
        messagebox.showinfo('消息', "已处理完成,请查看日志")

    else:
        messagebox.showerror('错误', "请先选择文件路径")


btn_encrypt = Button(l_frame_1, text='确定加密', command=btn_encrypt_click)
btn_encrypt.grid(row=3, column=1, padx=10, pady=10)

root.mainloop()

程序效果:

 

加密日志:

 

posted @ 2023-10-25 12:09  Levice  阅读(133)  评论(0编辑  收藏  举报