PHPEcel:如何改变行的颜色

ddarikpa  于 2023-04-19  发布在  PHP
关注(0)|答案(2)|浏览(236)

我想在PHPEcel上创建交替的颜色行。例如odd=no,even=color。

我的代码是:

$row = 4;
$excel->getActiveSheet()->getStyle('A4:I'.($row-1))->applyFromArray(
 array(
    'fill' => array(
        'type' => PHPExcel_Style_Fill::FILL_SOLID,
        'color' => array('rgb' => 'ccff99')
    )
 )
);

我对循环if even=color else no color感到困惑。

gk7wooem

gk7wooem1#

以下是我的解决方案:

所以你把数据设置到Excel中:

$excel->getActiveSheet()->fromArray($datas);

首先,对于表格标题,我应用了此填充和颜色(注意,您必须更改A1:I1,以满足您的需求)。

$excel->getActiveSheet()->getStyle('A1:I1')->applyFromArray(
    array(
        'fill' => array(
            'type' => \PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('argb' => 'FFCCFFCC')
        ),
        'borders' => array(
            'bottom' => array('style' => \PHPExcel_Style_Border::BORDER_THIN),
            'right' => array('style' => \PHPExcel_Style_Border::BORDER_MEDIUM)
        )
    )
);

然后,你做一个简单的循环,一行接一行地上色。当然,你这次从第二行开始,当你达到你的数据计数时结束。

for ($i = 2; $i < count($sub); $i++) {
    if ($i % 2 == 0) {
        $excel->getActiveSheet()->getStyle('A' . $i . ':I' . $i)->applyFromArray(
            array(
                'fill' => array(
                    'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('argb' => 'FFF3F3F3')
                ),
            )
        );
    }
}
wj8zmpe1

wj8zmpe12#

您可以对此问题使用条件格式。官方文档:https://phpspreadsheet.readthedocs.io/en/latest/topics/conditional-formatting/#formulae

$cellRange = 'A1:Z999';
$conditionalStyles = [];
$wizardFactory = new Wizard($cellRange);
/** @var Wizard\Expression $cellWizard */
$cellWizard = $wizardFactory->newRule(Wizard::EXPRESSION);
$style = $cellWizard->getStyle();
$style->getFill()->setFillType(Fill::FILL_SOLID)
    ->getStartColor()->setARGB('D9D9D9');

$cellWizard->formula('MOD(ROW(),2)')
    ->setStyle($style);
$conditionalStyles[] = $cellWizard->getConditional();

$spreadSheet->getActiveSheet()
    ->getStyle($cellWizard->getCellRange())
    ->setConditionalStyles($conditionalStyles);

或不使用向导的此方法

$conditional = new Conditional();
    $conditional->setConditionType(Conditional::CONDITION_EXPRESSION)
        ->setOperatorType(Conditional::OPERATOR_NONE)
        ->addCondition('MOD(ROW(),2)')
        ->getStyle()
        ->getFill()
        ->setFillType(Fill::FILL_SOLID)
        ->getStartColor()
        ->setRGB(self::EVEN_COLOR);
    $sheet->getStyle([1, $firstRow, $dimension, $lastRow])->setConditionalStyles([$conditional]);

相关问题