PHPExcel - 验证写入和保存是否成功



我已经成功地让PHPExcel编写了一个漂亮、格式良好的电子表格。我的问题是下一步该怎么办。如果文件写入成功并保存,我需要执行一些数据库更新。如果文件尚未写入,则不得进行这些更新。

我到处找了找,但找不到这方面的任何东西。

这是我当前的"写入"代码:

    $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
    $file['success'] = $objWriter->save($file['path'].$file['filename']);   

$file数组的其他部分在其他地方指定。通过这种方式,我可以将数组作为函数结果传递,并使用路径&文件名在我的代码的其他部分。当前$file['success']调试为NULL。

编辑:类内方法的结构

    public function export_ap_files {
    //fetch data to go into the XLS file
    $data = $this->get_invoices_for_payment();
    //build excel files
    if ( !empty($data['ap_invoices']) ) {
                    //code to build the XLSX is in another method
        $ap_xls = $this->export_ap_excel($data['ap_invoices']);
        //mark invoices as sent for payment - if the XLSX file has not been written then this bit should not proceed
        foreach ($data['ap_invoices'] as $invoice) {
            //CakePHP save code goes here
        }
    }
    die('done');
    }

PHPExcel在失败时抛出异常,因此将代码包装在try/catch块中

编辑

// fetch data to go into the XLS file
$data = $this->get_invoices_for_payment();
// build excel files
if ( !empty($data['ap_invoices']) ) {
    try {
        // code to build the XLSX is in another method
        $ap_xls = $this->export_ap_excel($data['ap_invoices']);
    } catch (Exception $e) {
        die('Failed to create Excel file: ' . $e->getMessage());
    }
    // mark invoices as sent for payment
    // if the XLSX file has not been written then this bit should not proceed
    foreach ($data['ap_invoices'] as $invoice) {
        //CakePHP save code goes here
    }
}
die('done');

最新更新