Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Created January 11, 2021 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspose-com-gists/647605e64f8abf8046f2c257f8d9ec4a to your computer and use it in GitHub Desktop.
Save aspose-com-gists/647605e64f8abf8046f2c257f8d9ec4a to your computer and use it in GitHub Desktop.
Protect and Unprotect Excel Files in Java
// Open the Excel file
Workbook workbook = new Workbook("workbook.xlsx");
// Protect workbook by specifying protection type
workbook.protect(ProtectionType.ALL, "12345");
// Save the file
workbook.save("workbook_protected.xlsx");
// Open the Excel file
Workbook workbook = new Workbook("workbook.xlsx");
// Accessing the first worksheet in the Excel file
WorksheetCollection worksheets = workbook.getWorksheets();
Worksheet worksheet = worksheets.get(0);
Protection protection = worksheet.getProtection();
// The following 3 methods are only for Excel 2000 and earlier formats
protection.setAllowEditingContent(false);
protection.setAllowEditingObject(false);
protection.setAllowEditingScenario(false);
// Protect the first worksheet with a password "1234"
protection.setPassword("1234");
// Save the file
workbook.save("Excel.xlsx");
// Open the Excel file
Workbook workbook = new Workbook("workbook_protected.xlsx");
// Unprotect workbook
workbook.unprotect("12345");
// Set password to null
workbook.getSettings().setPassword(null);
// Save the file
workbook.save("workbook_unprotected.xlsx");
// Open the Excel file
Workbook workbook = new Workbook("workbook.xlsx");
// Accessing the first worksheet in the Excel file
WorksheetCollection worksheets = workbook.getWorksheets();
Worksheet worksheet = worksheets.get(0);
// Unprotect worksheet
worksheet.unprotect("12345");
// Save the file
workbook.save("workbook_updated.xlsx");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment