I'm using openpyxl
to work with Microsoft Excel files (.xlsx/.xlsm), however I am struggling to lock cells (ie. prevent editing). My current code is this:
lock = Protection(locked=True,
hidden=False)
ws['A1'].protection = lock # ws is my worksheet
However, I am still able to edit cell A1
. How can I fix it?
Edit:
This link (to a openpyxl
email chain) recommends locking the entire sheet and then to unlock all of the cells but for A1
. However, this does not look like a reliable solution as I'll be dumping large amounts of data.
Lock the entire sheet:
ws.protection.sheet = True
Then unlock the cells that can be edited
cell.protection = Protection(locked=False)
You also need to set protection for the whole worksheet. The specification says this about protection for individual cells:
A boolean value indicating if the cell is locked. When cells are marked as "locked" and the sheet is protected, then the options specified in the Sheet Part's sheetProtection element (§18.3.1.85) are prohibited for these cells.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With