PHPExcel insert array formula

懵懂的女人 提交于 2020-04-11 04:55:26

问题


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.


回答1:


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!




回答2:


Since this question/answer still comes up when searching for PHPExcel's successor, PHPSpreadsheet, I'd like to add that the latter has support for array formulas build in. Just assign the formula as usual and set the type-attribute to array:

$attrs = $sheet->getCell("C1")->getFormulaAttributes();
$attrs['t'] = 'array';
$sheet->getCell("C1")->setFormulaAttributes($attrs);


来源:https://stackoverflow.com/questions/29174947/phpexcel-insert-array-formula

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!