如何使用PhpExcel处理异常?

时间:2012-03-21 04:28:19

标签: php exception-handling phpexcel

我正在为我的应用使用PhpExcel并看到错误。我试过处理异常 try{}catch(){}但它不起作用。如何使用PhpExcel处理异常?这是我的代码:

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();
    }
}

感谢帮助!

1 个答案:

答案 0 :(得分:2)

计算引擎应该抛出一个可以捕获的普通PHP异常。我用于调试计算引擎错误的前端逻辑是:

//  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>';
    }
}

这提供了很多关于计算引擎如何工作的附加信息,这在调试时非常有用。