PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 4, 2022

[FIXED] How to set DataValidation of a column in PHPExcel?

 October 04, 2022     php, phpexcel     No comments   

Issue

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:

  • PHPExcel Github issue
  • Relevant SO answer


Answered By - Janez Kuhar
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing