How to handle exception with PhpExcel?

13,159

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.

Share:
13,159
Davuz
Author by

Davuz

I love computer!

Updated on June 04, 2022

Comments

  • Davuz
    Davuz almost 2 years

    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!

    • F21
      F21 about 12 years
      Are you sure $val = $cell->getCalculatedValue(); is the line throwing the exception? Try wrapping $sheet=$excelObj->getActiveSheet(); $cell = $sheet->getCellByColumnAndRow(1, 10); in the try block as well.
    • Phil
      Phil about 12 years
      What's the exact error message?
    • Davuz
      Davuz about 12 years
      echo $e->getTraceAsTring() don't run. Error Message display : Cannot convert an bbject to int :| I'm using Yii framework
  • Davuz
    Davuz about 12 years
    Thank you so much! Perhaps this is solution that i need.