Oma*_*eed 6 python excel openpyxl
I am trying to password protect an entire Excel file (same functionality as File > Protect Workbook > Encrypt with Password) using Python.
I have come across openpyxl and the protection features it offers (https://openpyxl.readthedocs.io/en/stable/protection.html) seems to fulfill this need. I have the following code:
from openpyxl import Workbook
from openpyxl import load_workbook
test_spreadsheet = "test.xlsx"
wb = load_workbook(test_spreadsheet)
wb.security.workbookPassword = "password"
Run Code Online (Sandbox Code Playgroud)
However, I am getting the following error:
AttributeError: 'NoneType' object has no attribute 'workbookPassword'
Does anyone have an idea of what is causing this AttributeError? I have printed the sheetnames from wb and that is correctly printing the tabs in my Excel document.
对于默认构造的工作簿,该security属性默认初始化:
self.security = DocumentSecurity()
然而,通过阅读工作簿构建的工作簿不仅仅是默认构建的;而且是默认构建的。它们也由一个Parser对象操纵:
Parser.init默认构造 aWorkbook,但随后用源文档的属性覆盖特定属性:
self.wb.security = package.workbookProtection
这意味着对于没有安全设置的文件,导入的工作簿对象的属性值为None(security因此您的错误,因为None显然没有 attribute workbookPassword)。
然后,您的解决方案是创建一个 default WorkbookProtection(),将其分配给工作簿,然后设置工作簿密码。