Protect the Excel file using PHPExcel

How can I create password protected excel sheet using PHPExcel, I know how to protect excel sheet using

$G=$objPHPExcel->setActiveSheetIndex(0);
$G->getProtection()->setSheet(true);

But I am not getting any link how to set the password for editing protection only, means user can open the file without password but cannot remove the protection from sheet which can be easily done by any one from Data menu. Suggestions are welcomed.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

For Excel2007 Writer only:

Set workbook security:

$objPHPExcel->getSecurity()->setLockWindows(true);
$objPHPExcel->getSecurity()->setLockStructure(true);

$objPHPExcel->getSecurity()->setWorkbookPassword('secret');

Set worksheet security:

$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);
$objPHPExcel->getActiveSheet()->getProtection()->setSort(true);
$objPHPExcel->getActiveSheet()->getProtection()->setInsertRows(true);
$objPHPExcel->getActiveSheet()->getProtection()->setFormatCells(true);

$objPHPExcel->getActiveSheet()->getProtection()->setPassword('password');

Solution 2

At the time, PHPExcel does not support protecting sheets with a password.

Solution 3

Try these options which are not mentioned in Documentation.

$objPHPExcel->getActiveSheet()->getProtection()->setSelectLockedCells(true);
$objPHPExcel->getActiveSheet()->getProtection()->setSelectUnlockedCells(true);
$objPHPExcel->getActiveSheet()->getProtection()->setFormatCells(true);
$objPHPExcel->getActiveSheet()->getProtection()->setFormatRows(true);
$objPHPExcel->getActiveSheet()->getProtection()->setInsertColumns(true);
$objPHPExcel->getActiveSheet()->getProtection()->setInsertRows(true);
$objPHPExcel->getActiveSheet()->getProtection()->setInsertHyperlinks(true);
$objPHPExcel->getActiveSheet()->getProtection()->setDeleteColumns(true);
$objPHPExcel->getActiveSheet()->getProtection()->setDeleteRows(true);
$objPHPExcel->getActiveSheet()->getProtection()->setSort(true);
$objPHPExcel->getActiveSheet()->getProtection()->setAutofilter(true);
$objPHPExcel->getActiveSheet()->getProtection()->setObjects(true);
$objPHPExcel->getActiveSheet()->getProtection()->setScenarios(true);
$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);
$objPHPExcel->getActiveSheet()->getProtection()->setPassword('password');

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply