在实际工作中,遇到了大量excel文件需要加密,以防止check,于是就网上搜集了一些教程,自己简单写了一个
- # -*- coding: utf-8 -*-
- # --author:valecalida--
- from tkinter import filedialog, simpledialog, Tk
- from win32com.client import Dispatch
- from os import listdir
- from time import sleep
-
-
- def encrypto_excel(old_filename, new_filename, tmp_passwd, passwd_str=''):
- excel_tmp = Dispatch("Excel.Application")
- wb = excel_tmp.Workbooks.Open(old_filename, False, False, None, passwd_str)
- excel_tmp.DisplayAlerts = False
- wb.SaveAs(new_filename, None, tmp_passwd, '')
- wb.Close()
- excel_tmp.Quit()
-
-
- def get_file_path(data_dir):
- filename_sets = listdir(data_dir)
- filename = []
- for file_name in filename_sets:
- file_name_split = file_name.split('.')
- if file_name_split[-1] == 'xlsx' or file_name_split[-1] == 'xls':
- filename.append(file_name)
- return filename
-
-
- def main():
- root = Tk()
- root.withdraw()
- # filetypes=(("Excel files", "*.xlsx"),("Excel files", ".xls"))
- source_folder = filedialog.askdirectory(title='请选择要加密文件所在文件夹') + '/'
- file_list = get_file_path(source_folder)
- excel_tmp_passwd = simpledialog.askstring(title='密码设置', prompt='请输入想要设置的密码:')
- output_folder = filedialog.askdirectory(title='请选择输出另存的文件夹') + '/'
-
- for f_name in file_list:
- print("[*] " + f_name + ' 开始加密啦~')
- try:
- s_f = (source_folder + f_name).replace("/", "\\")
- # print(s_f)
- o_f = (output_folder + f_name).replace("/", "\\")
- # print(o_f)
- encrypto_excel(s_f, o_f, excel_tmp_passwd)
- print("[+] " + f_name + " 加密完成了,请注意查看哟~")
-
- except Exception as e:
- print(str(e) + f_name + '加密失败了,请手动设置')
-
- if __name__ == '__main__':
- main()
- sleep(3)
这里主要是三个功能点:
当然也有一点问题,这个只能加密没有密码的excel文件,如果有密码的话就会提示加密失败,后续再优化吧,下面是运行界面,输入文件夹路径
密码输入框
输出文件夹选择
2022.11.26更新最新版打包exe文件,见:https://download.csdn.net/download/valecalida/87166485