18

在phpexcel中,我能够通过

$objPHPExcel->getActiveSheet()->protectCells('A1:D1', 'php');
$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);

如果我双击 A1 到 D1 之间的任何单元格,它会要求输入密码。
但是,如果我双击任何其他单元格(例如)A2,它会说

"The cell or chart that you are trying to change is protected and therefore 
read-only".

它锁定整个工作表,是否可以仅锁定特定单元格并使其他单元格可编辑?

4

4 回答 4

22

最后,我找到了正确的方法来做到这一点..

$objPHPExcel = new PHPExcel;
$objSheet = $objPHPExcel->getActiveSheet();

//保护单元格范围

$objSheet->protectCells('A1:B1', 'PHP');

// 取消保护单元格范围

$objSheet->getStyle('A2:B2')->getProtection()
->setLocked(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED);

// 保护工作表

$objSheet->getProtection()->setSheet(true);

这是完美的工作!

于 2013-06-11T17:44:01.840 回答
4

sravis got me on the right track, but still one flaw remains: if you do it that way, you can still just remove the locking of the sheet using Excel without entering a password (just as it tells you when you click on a cell that's not locked with a password).

To lock an Excel-sheet with a password and unprotect a couple of cells, you need to protect the sheet (instead of just a couple of cells) and then unprotect some cells:

$sheet->getProtection()->setPassword('password hare');
$sheet->getProtection()->setSheet(true);
$sheet->getStyle('A1:B2')->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED);

That way the user will have to enter the password when trying to unprotect the sheet using Excel.

于 2013-07-18T10:15:56.493 回答
3

如果您现在使用的是 PHPExcel 的继任者 PhpSpreadsheet,

$sheet->getStyle('A1:B2')->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED)

将给出类未找到错误。

解决方案:

use PhpOffice\PhpSpreadsheet\Style\Protection;

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

$sheet->getStyle('A1:A10')->getProtection()
->setLocked(Protection::PROTECTION_UNPROTECTED);

这将起作用。

于 2018-07-31T07:57:17.797 回答
-2
/* this section lock for all sheet */
$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);

/*  and this section unlock cell rage('A2:Z2') from locked sheet */
$objPHPExcel->getActiveSheet()->getStyle('A2:Z500')->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED);
于 2016-11-25T07:49:25.433 回答