问题
I'm trying to read the cell formulas with rangetoArray() function and then there is array values return i want to sum it with the phpexcel library when this function read the range values.
include 'PHPExcel/Classes/PHPExcel.php';
include 'PHPExcel/Classes/PHPExcel/IOFactory.php'
$objPHPExcel = PHPExcel_IOFactory::load($uploadedFile);
$cellValues = $objPHPExcel->getActiveSheet()->rangeToArray('A1:A2');
//Basically i'm doing this for sum values in for each loop .. but it is custom created. i want PHPExcel Library Function for SUM and other Mathmatic Operations.
foreach ($cellValues as $cell) {
foreach ($cell as $finalValue) {
$sumVal += $finalValue;
}
}
//I want to read value through rangetoArray('A1:A5'); like this and automatic sum it with some PHPExcel Library function / method.
Thanks
回答1:
Option #1
Create a formula, assigning to a dummy cell (A1 in this case, though it doesn't change the value of cell A1 in any way), and using the calculation engine to execute that formula:
$sumFormula = '=SUM(A1:B2)';
$rangeSum = PHPExcel_Calculation::getInstance()->calculateFormula(
$sumFormula,
'A1',
$objPHPExcel->getActiveSheet()->getCell('A1')
);
var_dump($rangeSum);
Option #2
Call the SUM() function directly from your own code, passing the result of the toArray() method to the function:
$rangeSum = PHPExcel_Calculation_MathTrig::SUM(
$objPHPExcel->getActiveSheet()->rangeToArray('A1:B2')
);
var_dump($rangeSum);
Option #3
Create your own class which will take the result of a fromArray() call, with a doSum() method:
class mySummer{
protected $_cellArray;
public function __construct(array $cells = array()) {
$this->_cellArray = PHPExcel_Calculation_Functions::flattenArray($cells);
}
public function doSum(){
return array_sum($this->_cellArray);
}
}
$summer = new mySummer(
$objPHPExcel->getActiveSheet()->rangeToArray('A1:B2')
);
var_dump($summer->doSum());
来源:https://stackoverflow.com/questions/16770580/phpexcel-reading-cell-values-with-rangetoarray-function-and-apply-sum-formul