锁定或解锁形状

保护指定工作表中的所有形状

要保护指定工作表中的所有形状,请使用 Worksheet.protect(int type) 方法,如下面的示例代码所示。

String text = "This is a test";
Workbook workbook = new Workbook();
Worksheet worksheet = workbook.getWorksheets().get(0);
Shape shape = worksheet.getShapes().addTextBox(1, 0, 1, 0, 30, 100);
shape.setText(text);
shape = worksheet.getShapes().addRectangle(5, 0, 1, 0, 30, 100);
shape.setText(text);
shape = worksheet.getShapes().addButton(9, 0, 1, 0, 30, 100);
shape.setText(text);
shape = worksheet.getShapes().addOval(13, 0, 1, 0, 50, 100);
shape.setText(text);
//Protect all shapes in a specified worksheet
shape.getWorksheet().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("Locked.xlsx", SaveFormat.XLSX);

解锁受保护工作表中的指定形状

要解除对受保护工作表中的指定形状的锁定状态,请使用 shape.IsLockedshape.setLocked,如下面的示例代码所示。

注意:只有在工作表受保护时,shape.IsLockedshape.setLocked 才有意义。

Workbook workbook = new Workbook("Locked.xlsx");
//Get protected worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
//Get the specified shape to be unlocked
Shape shape = worksheet.getShapes().get("TextBox 1");
//Unlock the specified shape
if (!worksheet.getProtection().getAllowEditingObject() && shape.isLocked())
{
shape.setLocked(false);
}
workbook.save("UnLocked.xlsx", SaveFormat.XLSX);