我正在使用PHPExcel将XLSX文件导入我的相关数据库。但在运行该功能时,我收到错误。我的代码如下所示。
控制器:
<?php if (!defined ('BASEPATH')) exit ('No direct access allowed');
class ExcelController extends CI_Controller
{
public function index()
{
//load library excel
$this->load->library('excel');
//Here i used microsoft excel 2007
$objReader= PHPExcel_IOFactory::createReader('Excel2007');
//Set to read only
$objReader->setReadDataOnly(true);
//Load excel file
$objPHPExcel=$objReader->load('data.xls'); // error in this line
$objWorksheet=$objPHPExcel->setActiveSheetIndex(0);
//load model
$this->load->model('user_model');
//loop from first data untill last data
for($i=2;$i<=77;$i++)
{
$name= $objWorksheet->getCellByColumnAndRow(0,$i)->getValue();
$address= $objWorksheet->getCellByColumnAndRow(1,$i)->getValue();
$data_user=array('name'=>$name, 'username'=>$address);
$this->user_model->add_data($data_user);
}
}
}
?>
模型:
<?php
if (!defined ('BASEPATH')) exit ('No direct access allowed');
class User_model extends CI_Controller
{
public function __construct() {
parent::__construct();
}
public function add_data($data_user)
{
$this->load->database();
$this->db->insert('data',$data_user);
return $this->db->insert_id();
}
}
?>
我的代码出错:
Fatal error: Uncaught exception 'PHPExcel_Reader_Exception' with message 'Could not open data.xls for reading! File does not exist.' in C:\xampp\htdocs\ci_excel\application\third_party\PHPExcel\Reader\Excel2007.php:347 Stack trace: #0 C:\xampp\htdocs\ci_excel\application\controllers\excelcontroller.php(19): PHPExcel_Reader_Excel2007->load('data.xls') #1 [internal function]: ExcelController->index() #2 C:\xampp\htdocs\ci_excel\system\core\CodeIgniter.php(359): call_user_func_array(Array, Array) #3 C:\xampp\htdocs\ci_excel\index.php(202): require_once('C:\xampp\htdocs...') #4 {main} thrown in C:\xampp\htdocs\ci_excel\application\third_party\PHPExcel\Reader\Excel2007.php on line 347
答案 0 :(得分:2)
根据错误消息和您的评论判断,您看起来使用的文件路径不正确。
$objPHPExcel=$objReader->load('data.xls');
在CodeIgniter路径中,相对于条目脚本,通常是index.php。
使用此位置的相对文件路径,或者使用绝对路径。
答案 1 :(得分:0)
我认为你使用了错误的路径,改变了这个
$objPHPExcel=$objReader->load('data.xls'); // error in this line
要
$objPHPExcel=$objReader->load('./application/third_party/Excel5/data.xlsx');