编程语言
首页 > 编程语言> > PHPExcel条件格式内循环

PHPExcel条件格式内循环

作者:互联网

我试图将PHPExcel条件格式应用于值B小于50的列B中的所有单元格.我从开发人员文档中获取了示例,但到目前为止,我无法使其正常工作.有任何想法吗?

这是有条件的:

$objConditional1 = new PHPExcel_Style_Conditional(); 
$objConditional1->setConditionType(PHPExcel_Style_Conditional::CONDITION_CELLIS);
$objConditional1->setOperatorType(PHPExcel_Style_Conditional::OPERATOR_LESSTHAN);

$objConditional1->addCondition('50'); 
$objConditional1->getStyle()->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_RED); 
$objConditional1->getStyle()->getFont()->setBold(true);

这是循环:

$rowCount = 3;
foreach ($biocount as $value) {

$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $value);
$objPHPExcel->getActiveSheet()->getStyle('B'. $rowCount)->getFont()->setSize(14);
$objPHPExcel->getActiveSheet()->getStyle('B'. $rowCount)->setConditionalStyles($objConditional1);

$rowCount++;
      }

解决方法:

setConditionalStyles()需要条件样式数组,而不是单个条件样式对象

/**
 * Set Conditional Styles. Only used on supervisor.
 *
 * @param PHPExcel_Style_Conditional[] $pValue Array of condtional styles
 * @return PHPExcel_Style
 */

例如

$rowCount = 3;
foreach ($data as $value) {
    $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $value);
    $objPHPExcel->getActiveSheet()->getStyle('B'. $rowCount)
        ->getFont()->setSize(14);
    $objPHPExcel->getActiveSheet()->getStyle('B'. $rowCount)
        ->setConditionalStyles(array($objConditional1));
    $rowCount++;
}

编辑

请注意,您不必在循环中为每个单元格设置条件样式的开销,而是可以在完成循环后的一个步骤中使用duplicateConditionalStyle()方法将样式应用于一系列单元格

$rowCount = 3;
foreach ($data as $value) {
    $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $value);
    $objPHPExcel->getActiveSheet()->getStyle('B'. $rowCount)
        ->getFont()->setSize(14);
    $rowCount++;
}

$objPHPExcel->getActiveSheet()
    ->duplicateConditionalStyle(
        array($objConditional1), 
        'B3:B' .($rowCount - 1)
    );

标签:phpexcel,php,formatting
来源: https://codeday.me/bug/20191030/1968149.html