Home » excel » python – Is there a way to protect workbooks using openpyxl or xlswriter?

python – Is there a way to protect workbooks using openpyxl or xlswriter?

Posted by: admin May 14, 2020 Leave a comment


I’m trying to automate Excel reports, and I’d prefer users didn’t try to rename or reorder the worksheets. While I’ve had no problems protecting individual cells using xlsxwriter, I’ve failed to see an option to protect the workbook itself. I’m looking to openpyxl, but the tutorial does not seem to have any effect.

Edit: I’m now using this block of code, but does neither produce an error or protect my workbooks.

from openpyxl import load_workbook
from openpyxl.workbook.protection import WorkbookProtection

workbook = load_workbook(filepath, read_only=False, keep_vba=True)
workbook.security = WorkbookProtection(workbookPassword = 'secret-password', lockStructure = True)

By the way, I am dealing with .xlsm files. If there are any solutions or points that I’ve missed, please let me know.

How to&Answers:

From this code:

from openpyxl.workbook.protection import WorkbookProtection

myWorkbook.security = WorkbookProtection(workBookPassword = 'super-secret-password', lockStructure = True)


WorkbookProtection(workBookPassword = 'super-secret-password', lockStructure = True)


WorkbookProtection(workbookPassword = 'super-secret-password', lockStructure = True)

workBookPassword should be workbookPassword

Tested on Python32 3.8 and OpenPyXL version 3.0.2


Xlsxwriter has the option to protect the workbook with the command worksheet.protect() (have a look at the documentation: https://xlsxwriter.readthedocs.io/worksheet.html )

However take into consideration this:

Worksheet level passwords in Excel offer very weak protection. They do
not encrypt your data and are very easy to deactivate. Full workbook
encryption is not supported by XlsxWriter since it requires a
completely different file format and would take several man months to