Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock some cells from editing in python openpyxl

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.

like image 651
Uchiha Madara Avatar asked Oct 22 '17 17:10

Uchiha Madara


2 Answers

Lock the entire sheet:

    ws.protection.sheet = True

Then unlock the cells that can be edited

     cell.protection = Protection(locked=False)
like image 56
Siva Avatar answered Oct 12 '22 09:10

Siva


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.

like image 5
Charlie Clark Avatar answered Oct 12 '22 09:10

Charlie Clark