Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPExcel insert array formula

I want to insert this array formula:

{=SUM(IF(FREQUENCY(IF(T9:T977=1,MATCH(U9:U977,U9:U977,0)),ROW(U9:U977)-ROW(U9)+1),1))}

but when I'm using:

$sheet->getCell("C1")->setValue("{=SUM(IF(FREQUENCY(IF(T9:T977=1,MATCH(U9:U977,U9:U977,0)),ROW(U9:U977)-ROW(U9)+1),1))}");

It doesn't work, I've checked the documentation, but still haven't found anything.

like image 868
Max Allan Niklasson Avatar asked Nov 04 '25 12:11

Max Allan Niklasson


1 Answers

I couldn't find any answer so I went through PHPExcel and made myself a solution:

in /PHPExcel/Cell.php at row 251 in the switch($pDataType) add this:

case PHPExcel_Cell_DataType::TYPE_FORMULA_ARRAY:
$this->_value = (string)$pValue;
break;

in /PHPExcel/Cell/DataType.php add this constant:

const TYPE_FORMULA_ARRAY = 't';

At last in /PHPExcel/Writer/Excel2007/Worksheet.phpI've added this in the switch beginning at row 1095:

case 't':           // Array Formulae
    $objWriter->startElement('f');
    $objWriter->writeAttribute('t', 'array');
    $objWriter->writeAttribute('ref', $pCellAddress);
    $objWriter->writeAttribute('aca', '1');
    $objWriter->writeAttribute('ca', '1');
    $objWriter->text($cellValue);
    $objWriter->endElement();               
    if ($this->getParentWriter()->getOffice2003Compatibility() === false) {
        if ($this->getParentWriter()->getPreCalculateFormulas()) {
            $calculatedValue = $pCell->getCalculatedValue();
            if (!is_array($calculatedValue) && substr($calculatedValue, 0, 1) != '#') {
                $objWriter->writeElement('v', PHPExcel_Shared_String::FormatNumber($calculatedValue));
            } else {
                $objWriter->writeElement('v', '0');
            }
        } else {
            $objWriter->writeElement('v', '0');
    }
}
break;

Then I used the function like this:

$sheet->getCell("C1")->setValueExplicit("=SUM(IF(FREQUENCY(IF(T9:T977=1,MATCH(U9:U977,U9:U977,0)),ROW(U9:U977)-ROW(U9)+1),1))", PHPExcel_Cell_DataType::TYPE_FORMULA_ARRAY);

And it works all good when I'm creating a excel file!

like image 104
Max Allan Niklasson Avatar answered Nov 07 '25 08:11

Max Allan Niklasson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!