python使用pywin32模块给excel文件加密解密

import win32com.client

'''
本脚本加密解密excel只适用于windows平台
'''

def decrypt_excel(encrypt_excel_path, decrypt_excel_path, excel_key):
    xcl = win32com.client.DispatchEx('Excel.Application')
    xcl.DisplayAlerts = False
    wb = xcl.workbooks.open(
        encrypt_excel_path, False, True, None, excel_key)
    wb.SaveAs(decrypt_excel_path, None, '', '')
    wb.Close()
    xcl.Quit()

def encrypt_excel(decrypt_excel_path, encrypt_excel_path, excel_key):
    xcl = win32com.client.DispatchEx('Excel.Application')
    xcl.DisplayAlerts = False
    wb = xcl.workbooks.open(decrypt_excel_path, False, False, None)
    wb.SaveAs(encrypt_excel_path, None, excel_key, '') #excel支持打开加密和写修改加密两层,这里只设置了一层key
    wb.Close()
    xcl.Quit()

if __name__ == "__main__":
    excel_key = input("请输入excel文件的加密解密key:\n")
    if excel_key:
        ……
        # 读取加密文件,临时生成解密文件
        decrypt_excel(encrypt_excel_path, decrypt_excel_path, excel_key)
        # 将result excel加密
        encrypt_excel(result_path, result_path, excel_key)
        ……

函数参考链接:https://docs.microsoft.com/zh-cn/office/vba/api/excel.workbooks.open

You may also like...

发表评论