Search code examples
pythonexcelpython-3.xopenpyxlxlsxwriter

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


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)
workbook.save(filepath)

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


Solution

  • From this code:

    from openpyxl.workbook.protection import WorkbookProtection
    
    myWorkbook.security = WorkbookProtection(workBookPassword = 'super-secret-password', lockStructure = True)
    myWorkbook.save(filepath)
    

    Change:

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

    to:

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

    workBookPassword should be workbookPassword

    Tested on Python32 3.8 and OpenPyXL version 3.0.2