PHPExcel Codeigniter:致命错误:未捕获异常'PHPExcel_Reader_Exception'

时间:2015-11-16 13:35:52

标签: php codeigniter phpexcel fatal-error

我正在开发一个项目,我需要将数据从excel(.xlsx)文件导入到数据库中的表中。
我已经为控制器upload.php

编写了代码
    $this->load->library('excel');


    ini_set('memory_limit', '-1');


    $objReader = PHPExcel_IOFactory::createReader('Excel2007');



    $objReader->setReadDataOnly(true);



    $path = $_SERVER['DOCUMENT_ROOT'] . '/bitcoinreports/uploads/data.xlsx';


    $objPHPExcel=$objReader->load($path);


    $objWorksheet = $objPHPExcel->setActiveSheetIndex(0);

    //loop from first data until last data

    for($i=2; $i<=77; $i++){
    $name = $objWorksheet->getCellByColumnAndRow(0,$i)->getValue();
    $email = $objWorksheet->getCellByColumnAndRow(1,$i)->getValue();
    $phone = $objWorksheet->getCellByColumnAndRow(2,$i)->getValue();
    $details = $objWorksheet->getCellByColumnAndRow(3,$i)->getValue();   
    $location = $objWorksheet->getCellByColumnAndRow(4,$i)->getValue();
    $data_user = array(
    "name" => $name,
    "email" => $email ,
    "phone" => $phone ,
    "details" => $details ,
    "location" => $location ,
    );
    $this->dashboard_model->add_data($data_user);
  }

每当我打电话给这个控制器时,我都会收到以下错误

Fatal error:  Uncaught exception 'PHPExcel_Reader_Exception' with message 'Could not open C:/xampp/htdocs/bitcoinreports/uploads/data.xlsx for reading! File does not exist.' in C:\xampp\htdocs\bitcoinreports\application\third_party\PHPExcel\Reader\Excel2007.php:347
Stack trace:
#0 C:\xampp\htdocs\bitcoinreports\application\controllers\admin\upload.php(40): PHPExcel_Reader_Excel2007->load('C:/xampp/htdocs...')
#1 [internal function]: Upload->index()
#2 C:\xampp\htdocs\bitcoinreports\system\core\CodeIgniter.php(359): call_user_func_array(Array, Array)
#3 C:\xampp\htdocs\bitcoinreports\index.php(202): require_once('C:\\xampp\\htdocs...')
#4 {main}
  thrown in C:\xampp\htdocs\bitcoinreports\application\third_party\PHPExcel\Reader\Excel2007.php on line 347

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

在打开文件之前,检查它是否存在,并且对于运行PHP的进程是可读的(在这种情况下为xampp。不确定用户是如何在xampp中命名的,也许是apache)。

http://php.net/manual/en/function.is-readable.php

is_readable - 判断文件是否存在且可读

所以替换这个:

$objPHPExcel=$objReader->load($path);

if (is_readable($path)){
  $objPHPExcel=$objReader->load($path);
} else {
  // handle problem, for example
  echo "cannot read $path";
  exit;
}