I'm using CakePHP 3.2 and PHPExcel
library to import data from excel sheet to database.
I have the library at
/vendor/PHPExcel/Classes/PHPExcel.php
/vendor/PHPExcel/Classes/PHPExcel/IOFactory.php
and the action in controller is
public function bulkUpload()
{
$inputFileName = $this->request->data('excel_data');
//debug($inputFileName['name']);
if ($inputFileName != '') {
$inputFileType = \PHPExcel_IOFactory::identify($inputFileName);
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($inputFileName);
$objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
$highestRow = $objWorksheet->getHighestRow();
for ($row = 2; $row <= $highestRow; ++$row) {
$this->data['Program']['cycle_month'] = $objWorksheet->getCellByColumnAndRow(1, $row)->getValue();
$this->data['Program']['cycle_year'] = $objWorksheet->getCellByColumnAndRow(2, $row)->getValue();
$this->data['Program']['media_partnum'] = $objWorksheet->getCellByColumnAndRow(3, $row)->getValue();
$resultArray[$row-2] = $this->data['Program'];
}
debug($resultArray);
}
}
But this gives error as
pathinfo() expects parameter 1 to be string,
array given [ROOT/vendor/PHPExcel/Classes/PHPExcel/IOFactory.php, line 225]
and
file_exists() expects parameter 1 to be a valid path,
array given [ROOT/vendor/PHPExcel/Classes/PHPExcel/Reader/Excel2007.php, line 72]
and on debug($inputFileName);
it gives
[
'name' => 'testing.xlsx',
'type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'tmp_name' => '/tmp/phpvDWDxG',
'error' => (int) 0,
'size' => (int) 5247
]
replacing $inputFileName;
with $inputFileName['name']
in
$inputFileType = \PHPExcel_IOFactory::identify($inputFileName);
removes above two error but gives error as
Could not open testing.xlsx for reading! File does not exist.
Here, testing.xlsx
is the file I'm selecting from form
You need to add file like below:
require_once(ROOT. DS .'vendor'.DS.'PHPExcel/Classes/PHPExcel.php');
require_once(ROOT . DS . 'vendor' . DS.'PHPExcel/Classes/PHPExcel/IOFactory.php');
y0ou also need to add a namespace like below
use PHPExcel;
use IOFactory;
Now you can access excel class library and easily read and write
i am using this in my project.
you can try.
Thanks :)