Search code examples
phpspreadsheetphpoffice

How to protect individual cell using phpspreadsheet


I want to protect particular cell content from being amended. When I tried to protect whole sheet, no problem.

$sheet->getProtection()->setSheet(true)->setDeleteRows(true);

But, could not set protection for individual cell. I tried the following codes.

$sheet->protectCellsByColumnAndRow(0, 1, 100, 100, 'asdf');
$sheet->protectCells('A1','password',false);

Thanks in advance.


Solution

  • Here is the solution. First, enable the worksheet protection. Then, unlock all the cells by changing the default style of spreadsheet's protection. After that, lock the cell you want by specifying the cell's coordinate. The worksheet protection applied to locked cell only. So, the cell that you locked could not be edited anymore when you open that worksheet.

    $spreadsheet->getActiveSheet()->getProtection()->setSheet(true);
    $spreadsheet->getDefaultStyle()->getProtection()->setLocked(false);
    $spreadsheet->getStyle('A1')->getProtection()->setLocked(
        \PhpOffice\PhpSpreadsheet\Style\Protection::PROTECTION_PROTECTED
    );
    

    Helpful links: