Setting security on a spreadsheet
Excel offers 3 levels of "protection":
- Document: allows you to set a password on a complete spreadsheet, allowing changes to be made only when that password is entered.
- Worksheet: offers other security options: you can disallow inserting rows on a specific sheet, disallow sorting, ...
Cell: offers the option to lock/unlock a cell as well as show/hide the internal formula.
An example on setting document security:
$spreadsheet->getSecurity()->setLockWindows(true);
$spreadsheet->getSecurity()->setLockStructure(true);
$spreadsheet->getSecurity()->setWorkbookPassword("PhpSpreadsheet");
An example on setting worksheet security:
$spreadsheet->getActiveSheet()->getProtection()->setPassword('PhpSpreadsheet');
$spreadsheet->getActiveSheet()->getProtection()->setSheet(true);
$spreadsheet->getActiveSheet()->getProtection()->setSort(true);
$spreadsheet->getActiveSheet()->getProtection()->setInsertRows(true);
$spreadsheet->getActiveSheet()->getProtection()->setFormatCells(true);
An example on setting cell security:
$spreadsheet->getActiveSheet()->
getStyle('B1')->
getProtection()->
setLocked(\PhpOffice\PhpSpreadsheet\Style\Protection::PROTECTION_UNPROTECTED);
Make sure you enable worksheet protection if you need any of the worksheet protection features! This can be done using the following code:
$spreadsheet->getActiveSheet()->getProtection()->setSheet(true);