protect method
Protect the worksheet with specific protection options and password.
//Create a new Excel Document.
final Workbook workbook = Workbook();
// Accessing sheet via index.
final Worksheet sheet = workbook.worksheets[0];
final Range range = sheet.getRangeByName('A1');
range.setText('Worksheet Protected');
// ExcelSheetProtectionOption.
final ExcelSheetProtectionOption options = ExcelSheetProtectionOption();
options.all = true;
// Protecting the Worksheet by using a Password.
sheet.protect('Password', options);
//Save and Dispose.
final List<int> bytes = workbook.saveAsStream();
saveAsExcel(bytes, 'ExcelworksheetProtectionAllOption1.xlsx');
workbook.dispose();
Implementation
void protect(String password, [ExcelSheetProtectionOption? options]) {
if (_isPasswordProtected) {
throw Exception(
'Sheet is already protected, before use unprotect method');
}
if (password.length > _maxPassWordLength) {
throw Exception(
"Length of the password can't be more than $_maxPassWordLength");
}
if (options == null) {
options = ExcelSheetProtectionOption();
options.content = true;
options.lockedCells = true;
options.unlockedCells = true;
}
if (options.all == true) {
options.content = true;
options.objects = true;
options.scenarios = true;
options.formatCells = true;
options.formatColumns = true;
options.formatRows = true;
options.insertColumns = true;
options.insertRows = true;
options.insertHyperlinks = true;
options.deleteColumns = true;
options.deleteRows = true;
options.lockedCells = true;
options.sort = true;
options.useAutoFilter = true;
options.usePivotTableAndPivotChart = true;
options.unlockedCells = true;
}
_prepareProtectionOptions(options);
_flag.add(!options.content);
_flag.add(!options.objects);
_flag.add(!options.scenarios);
_flag.add(!options.formatCells);
_flag.add(!options.formatColumns);
_flag.add(!options.formatRows);
_flag.add(!options.insertColumns);
_flag.add(!options.insertRows);
_flag.add(!options.insertHyperlinks);
_flag.add(!options.deleteColumns);
_flag.add(!options.deleteRows);
_flag.add(!options.lockedCells);
_flag.add(!options.sort);
_flag.add(!options.useAutoFilter);
_flag.add(!options.usePivotTableAndPivotChart);
_flag.add(!options.unlockedCells);
_advancedSheetProtection(password);
final int usPassword =
(password.isNotEmpty) ? _getPasswordHash(password) : 1;
_isPassword = usPassword;
_isPasswordProtected = true;
}