import msoffcrypto
import os
encrypted_file = r"已加密Excel文件路径"
unencrypted_file = r"未加密文件将保存的路径"
excel_passwords = ["密码1", "密码2"]
def decrypt_excel(encrypted_file, unencrypted_file, excel_passwords):
for password in excel_passwords:
try:
with open(encrypted_file, "rb") as encrypted_file_fd:
office_file = msoffcrypto.OfficeFile(encrypted_file_fd)
office_file.load_key(password=password)
with open(unencrypted_file, "wb") as unencrypted_file_fd:
office_file.decrypt(unencrypted_file_fd)
print(f"文件已使用密码'{password}'解密并保存至:{unencrypted_file}")
break
except msoffcrypto.exceptions.InvalidKeyError:
continue
except msoffcrypto.exceptions.FileFormatError:
with open(unencrypted_file, "wb") as unencrypted_file_fd:
unencrypted_file_fd.write(open(encrypted_file, "rb").read())
break
except Exception as e:
print(f"解密过程中发生错误:{e}")
break
directory_path = r"G:\路径加密"
for root, dirs, files in os.walk(directory_path):
for file in files:
print(os.path.join(root, file))
m=r'{}'.format(os.path.join(root, file))
outm=r'{}'.format(os.path.join(root.replace('加密',''),file))
decrypt_excel(m,outm,excel_passwords)