protect method

void protect(
  1. String password, [
  2. ExcelSheetProtectionOption? options
])

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;
}