Protect the Excel File Using PHPexcel

Protect the Excel file using PHPExcel

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');

Can I create Excel file with password protection

You can use (the excellent) PHPExcel for this. To lock a whole workbook:

$reader = new PHPExcel_Reader_Excel2007;
$workbook = $reader->load("document.xlsx");
$workbook->getSecurity()->setWorkbookPassword("your password");

Or to lock a sheet:

$reader = new PHPExcel_Reader_Excel2007;
$workbook = $reader->load("document.xlsx");
$workbook->-getActiveSheet()->getSecurity()->setWorkbookPassword("your password");

Open a password protected EXCEL in wamp using PHP

If you are working only on Excel files, I recommend using the PHPExcel module, available here
You can open password protected sheets since the 1.8.0 release I think

PHPExcel lock particular cell

Finally, i found the right way to do it..

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

//PROTECT THE CELL RANGE

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

// UNPROTECT THE CELL RANGE

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

// PROTECT THE WORKSHEET SHEET

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

This is working perfectly!

PhpExcel write/save onto existing excel file

excel5 is for xls ( excel2007 is for xlsx)

Hence, change the write to excel block to

$fetched->fromArray($exceldatas, null, 'A1', true);
$objWriter = PHPExcel_IOFactory::createWriter($readphpexcel, 'Excel2007');// Excel 2010
$objWriter->save("polimer_uzex.xlsx");

How to verify the password in PHPExcel generated .xls file?

You should be able to use

$hash = $sheet->getProtection()->getPassword(); // returns a hash
$valid = ($hash === PHPExcel_Shared_PasswordHasher::hashPassword($password));

if($valid) {
//
}


Related Topics



Leave a reply



Submit