lock a row or a cell

4,361 views
Skip to first unread message

asiansp...@gmail.com

unread,
Feb 5, 2015, 11:23:36 AM2/5/15
to openpyx...@googlegroups.com
Hi,

I am able to lock a whole sheet, but I cannot lock individual rows or cells.  Is this possible?  If so, would you please give an example?

Thanks.

Charlie Clark

unread,
Feb 5, 2015, 11:32:56 AM2/5/15
to openpyx...@googlegroups.com
You can always the protection for any StyleableObject but the behaviour
isn't possibly what you expect because of the way it interacts with sheet
protection.

2.2 syntax

from openpyxl.styles import Protection

cell = ws['A1']
cell.protection = Protection(locked=False) # default is True because a
cell will be locked if a worksheet is locked otherwise it has no effect

I'm not really familiar with doing this much in code. You're probably best
off looking at Excel docs and the dialog box in Excel to see how the
settings interact.

Charlie
--
Charlie Clark
Managing Director
Clark Consulting & Research
German Office
Kronenstr. 27a
Düsseldorf
D- 40217
Tel: +49-211-600-3657
Mobile: +49-178-782-6226

asiansp...@gmail.com

unread,
Feb 5, 2015, 3:09:42 PM2/5/15
to openpyx...@googlegroups.com
Thanks.  That worked.

The idea is, to lock only certain cells, you first lock the sheet, and then unlock all the cells you don't need to protect.  That leaves the cells you do want to lock remain locked.

Code below:

from openpyxl import Workbook

from openpyxl.styles import Protection, Style

# I just want to lock cell1

wb = Workbook()

ws = wb.active

ws.protection.sheet = True

cell1 = ws['a1']

cell1.value = "Can you change me?"

cell2 = ws['a2']

cell2.value = "what about me?"

cell2.style = Style(protection = Protection(locked=False))

wb.save(filename = 'simple.xlsx')

Charlie Clark

unread,
Feb 6, 2015, 1:35:48 PM2/6/15
to openpyx...@googlegroups.com
Am .02.2015, 21:09 Uhr, schrieb <asiansp...@gmail.com>:

> Thanks. That worked.
> The idea is, to lock only certain cells, you first lock the sheet, and
> then
> unlock all the cells you don't need to protect. That leaves the cells
> you
> do want to lock remain locked.

Great you got it working. How about a pull request for the documentation
with the details? ;-)

Vijay Suman

unread,
Apr 1, 2021, 12:39:24 PM4/1/21
to openpyxl-users
not working in python 3.9.2
Reply all
Reply to author
Forward
0 new messages