如何使用PhpExcel处理异常? [英] How to handle exception with PhpExcel?

查看:116
本文介绍了如何使用PhpExcel处理异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

感谢帮助!

推荐答案

计算引擎应该抛出一个正常的PHP异常,这是catcheable。用于调试计算引擎错误的前端逻辑是:

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.

这篇关于如何使用PhpExcel处理异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆