问题
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.php
I'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