python知道EXCEL密码利用msoffcrypto批量取消密码

因为单位有很多原数据是加密的,正好正在自学python索性拿来练手,如果用VBA应该比这个简单毕竟是配套宏软件。话不多少上代码(版本python3.11.5)

import shutil
import msoffcrypto
import pathlib
import os
clientpath=str(input("请将需要取消密码的文件路径粘贴在对话框内\n"))
destination_path=str(input('请输入需要转出的路径\n'))
url=pathlib.Path(clientpath)
Excel_files=list(url.glob("*.xlsx"))                                    #glob()方法返回当前路径对象内与填入格式相同的类型的所有文件路径(二进制)
print(len(Excel_files))
a=len(Excel_files)
def unlock(filename,password,output_folder):
    temp=open(filename,"rb")
    excel=msoffcrypto.OfficeFile(temp)                                  #读取带有密码保护的文件
    if excel.type == "plain":
        out_path = pathlib.Path(output_folder)                          # 导出连接
        if not out_path.exists():                                       # 如果路径不存在则创建路径,如果存在则跳过
            out_path.mkdir()
        shutil.copy(str(filename),str(out_path/filename.name))
        temp.close()
    else:
        excel.load_key(password)                                        #键入密码
        out_path=pathlib.Path(output_folder)                            #导出连接
        if not out_path.exists():                                       #如果路径不存在则创建路径,如果存在则跳过
            out_path.mkdir()
        with open(str(out_path/filename.name),'wb') as f:               #斜杠/为合并符号
            excel.decrypt(f)                                            #decrypt()删除密码方法
            temp.close()
            
            
for i in Excel_files:                                               

        unlock(i,'03909454',destination_path)
print('success')
os.startfile(destination_path)                                      #将输出文件夹置顶窗口

这里面msoffcrypto库可以在win命令提示符窗口输入pip install msoffcrypto-tool 将会自动下载安装该库,其他的可以通过pycharm安装或者自行搜索对应库安装即可。

你可能感兴趣的:(python,excel,开发语言)