I havent found much of the topic of creating a password protected Excel file using Python.
In Openpyxl, I did find a SheetProtection
module using:
from openpyxl.worksheet import SheetProtection
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'
...
Does anyone know if such a request is even possible with Python? Thanks!
Looking at the docs for
openpyxl
, I noticed there is indeed aopenpyxl.worksheet.SheetProtection
class. However, it seems to be already part of a worksheet object:Checking
dir(ws.protection)
shows there is a methodset_password
that when called with a string argument does indeed seem to set a protected flag.I opened
random.xlsx
in LibreOffice and the sheet was indeed protected. However, I only needed to toggle an option to turn off protection, and not enter any password, so I might be doing it wrong still...openpyxl is unlikely ever to provide workbook encryption. However, you can add this yourself because Excel files (xlsx format version >= 2010) are zip-archives: create a file in openpyxl and add a password to it using standard utilities.