Search code examples
phpphpexcel

How to set DataValidation of a column in PHPExcel?


I am trying to create an Excel spreadsheet using PHPExcel.

I would like to validate a specific column. I know how to validate a cell, but I can't seem to find a method for validating a column. Can I do better than manually looping through all cells of a column?

require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';<br/>

$filename='test.xlsx';<br/>
if(file_exists($filename)){<br/>
    unlink($filename);<br/>
}

$objExcel = new PHPExcel();<br/>
$objWriter = new PHPExcel_Writer_Excel5($objExcel);<br/>
$objExcel->setActiveSheetIndex(0);<br/>
$objActSheet = $objExcel->getActiveSheet();<br/>
$objValidation = $objActSheet->getCell("A1")->getDataValidation(); //这一句为要设置数据有效性的单元格<br/>
$objValidation->setType(PHPExcel_Cell_DataValidation::TYPE_LIST)<br/>
        ->setErrorStyle(PHPExcel_Cell_DataValidation::STYLE_INFORMATION)<br/>
        ->setAllowBlank(false)<br/>
        ->setShowInputMessage(true)<br/>
        ->setShowErrorMessage(true)<br/>
        ->setShowDropDown(true)<br/>
        ->setErrorTitle('输入的值有误')<br/>
        ->setError('您输入的值不在下拉框列表内.')<br/>
        ->setFormula1('"列表项1,列表项2,列表项3"')<br/>
        ->setPromptTitle('设备类型');<br/>

$objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');<br/>

$objWriter->save('test.xlsx');<br/>

Solution

  • Yes, you can do better!

    For example if you want to apply validation on cells A1:A10, this will do the job:

    $objActSheet->setDataValidation("A1:A10", $objValidation);
    

    Sources: