openpyxl: password protect entire excel file (xlsx)

Viewed 5851

I am trying to find pythonic ways to encrypt/password-protect excel xlsx files. Came across openpyxl, where in their documentation (https://openpyxl.readthedocs.io/en/stable/protection.html) states that it can do so.

However, an error message AttributeError: 'NoneType' object has no attribute 'workbookPassword' is prompted when I executed the following. Help anyone?

from openpyxl import workbook

file = 'test.xlsx' // an existing xlsx
wb = load_workbook(filename = file)

wb.security.workbookPassword = 'test_password'
wb.security.lockStructure = True

Edit: I believe I have used the function improperly, though it is not v clear in their documentation. It was also mentioned that the password can be set using this function openpyxl.workbook.protection.WorkbookProtection.workbookPassword(), which then differs in their example.

1 Answers

You are talking about ways to "encrypt/password-protect excel xlsx files" in a synonymous manner. However, please note that regarding MS Office these are not the same (although one may argue about the wording here)! This can be seen from the screenshot below, or simply open an excel file and go to "File", then under Permissions click on "Protect Workbook".

Screenshot Excel Protection

The workbookPassword from openpyxl only prevents modifications of the workbook structure. Their documentation states, that this is only meant

To prevent other users from viewing hidden worksheets, adding, moving, deleting, or hiding worksheets, and renaming worksheets, you can protect the structure of your workbook with a password.

See also their documentation here.

This only refers to the structure, i.e. to adding/removing sheets, but it explicitly does not forbid users from reading the file, nor from editing the contents of the (already available) sheets! However, the set password does not offer read protection in the sense of an encryption.

I have not found a way to actually encrypt an Excel file with openpyxl, but other packages might do just that. I know encrypted files can be decrypted using Python, see e.g. this post. Therefore, I am guessing you can also encrypt such files in a similar way, although sadly right now I cannot test this.

Related