How to handle exception with PhpExcel?

谁说胖子不能爱 提交于 2019-12-08 04:13:09

问题


I'm using PhpExcel for my app and see a error. I've tried handling exception with try{}catch(){} but it doesn't work. How to handle exception with PhpExcel? Here is my code:

function import($excelObj) {
    $sheet=$excelObj->getActiveSheet();
    $cell = $sheet->getCellByColumnAndRow(1, 10);//assume we need calculate at col 1, row 10

    try {
        //This line seen error, but cannot echo in catch.
        $val = $cell->getCalculatedValue(); // $cell contain a formula, example: `=A1+A6-A8` 
                                            // with A1 is constant, A6 is formula `=A2*A5` 
                                            // and A8 is another `=A1/(A4*100)-A7`
        return $val;
    } catch (Exception $e) {
        echo $e->getTraceAsTring();
    }
}

Thank for helps!


回答1:


The calculation engine should throw a normal PHP exception that is catcheable. The front-end logic that I use for debugging calculation engine errors is:

//  enable debugging
PHPExcel_Calculation::getInstance()->writeDebugLog = true;

$formulaValue = $sheet->getCell($cell)->getValue();
echo '<b>'.$cell.' Value is </b>'.$formulaValue."<br />\n";

$calculate = false;
try {
    $tokens = PHPExcel_Calculation::getInstance()->parseFormula($formulaValue,$sheet->getCell($cell));
    echo '<b>Parser Stack :-</b><pre>';
    print_r($tokens);
    echo '</pre>';
    $calculate = true;
} catch (Exception $e) {
    echo "PARSER ERROR: ".$e->getMessage()."<br />\n";

    echo '<b>Parser Stack :-</b><pre>';
    print_r($tokens);
    echo '</pre>';
}

if ($calculate) {
    //  calculate
    try {
        $cellValue = $sheet->getCell($cell)->getCalculatedValue();
    } catch (Exception $e) {
        echo "CALCULATION ENGINE ERROR: ".$e->getMessage()."<br />\n";

        echo '<h3>Evaluation Log:</h3><pre>';
        print_r(PHPExcel_Calculation::getInstance()->debugLog);
        echo '</pre>';
    }
}

This gives a lot of additional information about how the calculation engine works, that can be extremely useful when debugging.



来源:https://stackoverflow.com/questions/9798596/how-to-handle-exception-with-phpexcel

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