PHPExcel : Reading cell values with rangetoArray() function and apply sum formula

。_饼干妹妹 提交于 2019-12-13 15:24:17

问题


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

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