Reputation: 4728
How can I disable a couple of cells but keep the rest editable, using the PHPExcel library? I tried a few combinations using:
$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);
$objPHPExcel->getActiveSheet()->getProtection()->setFormatCells(true);
$objPHPExcel->getActiveSheet()
->getStyle('A1:Z50')
->getProtection()->setLocked(
\PHPExcel_Style_Protection::PROTECTION_UNPROTECTED
);
$objPHPExcel->getActiveSheet()
->getStyle('C7:E7')
->getProtection()->setLocked(
\PHPExcel_Style_Protection::PROTECTION_PROTECTED
);
$objPHPExcel->getActiveSheet()->getProtection()->setSheet(false);
$objPHPExcel->getActiveSheet()->getProtection()->setFormatCells(false);
but all I can get is all document disabled or enabled. I'm pretty sure this can be achieved easily. Thanks in advance.
Upvotes: 2
Views: 5629
Reputation: 39414
Solution that protects a whole sheet, while keeping particular cells editable:
$excel->getActiveSheet()->getProtection()->setSheet(true);
$excel->getActiveSheet()->getStyle('A12:D50')->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED);
Complete example. In the resulting file, I can edit only cells B2, C2, and D2:
$excel = new PHPExcel();
$excel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D2', 'world!')
;
$excel->getActiveSheet()
->getProtection()->setSheet(true);
$excel->getActiveSheet()->getStyle('B2:D2')
->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED);
$writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
$writer->save(str_replace('.php', '.xls', __FILE__));
Upvotes: 3