Lock or unlock shapes
Sometimes, you need to protect all shapes in certain worksheets to prevent them from being destroyed by unwanted situations. In this case, you need to lock all shapes in the specified worksheet.
Sometimes, you need to be able to modify certain shapes in certain protected worksheets, in which case, you need to unlock these shapes.
This article will introduce in detail how to lock and unlock specified shapes.
Protect all shapes in a specified worksheet
To protect all shapes in a specified worksheet, use the Worksheet.Protect(type) method, as shown in the following sample code.
from aspose.cells import Workbook, FileFormatType,SaveFormat,ProtectionType | |
text = "This is a test"; | |
workbook = Workbook(); | |
worksheet = workbook.worksheets.get(0); | |
shape = worksheet.shapes.add_text_box(1, 0, 1, 0, 30, 100); | |
shape.text = text; | |
shape = worksheet.shapes.add_rectangle(5, 0, 1, 0, 30, 100); | |
shape.text = text; | |
shape = worksheet.shapes.add_button(9, 0, 1, 0, 30, 100); | |
shape.text = text; | |
shape = worksheet.shapes.add_oval(13, 0, 1, 0, 50, 100); | |
shape.text = text; | |
#Protect all shapes in a specified worksheet | |
shape.worksheet.protect(ProtectionType.OBJECTS);#Protects the entire worksheet. | |
#or shape.worksheet.protect(ProtectionType.All);//Protects all shapes in the specified worksheet. | |
#or worksheet.protect(ProtectionType.Objects);//Protects the entire worksheet. | |
#or worksheet.protect(ProtectionType.All);//Protects all shapes in the specified worksheet. | |
workbook.save(r"Locked.xlsx", SaveFormat.XLSX); |
Unlock specified shapes in a protected worksheet
To unlock a specified shape in a protected worksheet, use shape.is_locked, as shown in the following sample code.
Note: shape.is_locked is meaningful only when the worksheet is protected.
from aspose.cells import Workbook, FileFormatType,SaveFormat,ProtectionType | |
workbook = Workbook(r"Locked.xlsx") | |
#Get protected worksheet | |
worksheet = workbook.worksheets[0] | |
#Get the specified shape to be unlocked | |
shape = worksheet.shapes[0] | |
#Unlock the specified shape | |
if (not worksheet.protection.allow_editing_object and shape.is_locked): | |
shape.is_locked = False; | |
workbook.save(r"UnLocked.xlsx", SaveFormat.XLSX); |