使用Python的密码保护Excel文件 [英] Password Protecting Excel file using Python

查看:195
本文介绍了使用Python的密码保护Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还没有发现使用Python创建受密码保护的Excel文件的许多主题.

I havent found much of the topic of creating a password protected Excel file using Python.

在Openpyxl中,我确实使用以下命令找到了SheetProtection模块:

In Openpyxl, I did find a SheetProtection module using:

from openpyxl.worksheet import SheetProtection

但是,问题是我不确定如何使用它.它不是WorkbookWorksheet的属性,所以我不能只是这样做:

However, the problem is I'm not sure how to use it. It's not an attribute of Workbook or Worksheet so I can't just do this:

wb = Workbook()
ws = wb.worksheets[0]
ws_encrypted = ws.SheetProtection()
ws_encrypted.password = 'test'
...

有人知道Python是否可以发出这样的请求?谢谢!

Does anyone know if such a request is even possible with Python? Thanks!

推荐答案

这是我使用的解决方法.它会生成一个VBS脚本,并从您的python脚本中调用它.

Here's a workaround I use. It generates a VBS script and calls it from within your python script.

def set_password(excel_file_path, pw):

    from pathlib import Path

    excel_file_path = Path(excel_file_path)

    vbs_script = \
    f"""' Save with password required upon opening

    Set excel_object = CreateObject("Excel.Application")
    Set workbook = excel_object.Workbooks.Open("{excel_file_path}")

    excel_object.DisplayAlerts = False
    excel_object.Visible = False

    workbook.SaveAs "{excel_file_path}",, "{pw}"

    excel_object.Application.Quit
    """

    # write
    vbs_script_path = excel_file_path.parent.joinpath("set_pw.vbs")
    with open(vbs_script_path, "w") as file:
        file.write(vbs_script)

    #execute
    subprocess.call(['cscript.exe', str(vbs_script_path)])

    # remove
    vbs_script_path.unlink()

    return None

这篇关于使用Python的密码保护Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆