简体   繁体   中英

Import Excel file to MySQL using PHP Yii2

I just want to import data from excel (xls, xlsx) to mySql db in Yii2 using PHPExcel. This is my code in Controller:

$modelFile ->file = $firstName. '_' .$middleName. '_' .date('Y-m-d'). '_' .$file ->getBaseName(). "." .$file ->getExtension();
$objPHPExcel = new \PHPExcel();
$inputFiles = fopen("../file/".$modelFile ->file, "r");

try {
  $inputFileType = \PHPExcel_IOFactory::identify($inputFiles);
  $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
  $objPHPExcel = $objReader ->load($inputFiles);
} catch (Exception $ex) {
  die('Error');
}

$sheet = $objPHPExcel ->getSheet(0);
$highestRow = $sheet ->getHighestRow();
$highestColumn = $sheet ->getHighestColumn();

//$row is start 2 because first row assigned for heading.         
for ($row = 2; $row <= $highestRow; ++$row) {

  $rowData = $sheet ->rangeToArray('A'.$row. ':' .$highestColumn.$row, NULL, TRUE, FALSE);

  //save to branch table.
  $modelHeader = new FakturOut();
  $modelDetail = new FakturOutDetail();

  $modelHeader ->name = $rowData[0][0];
  $modelHeader ->age = $rowData[0][1];
  $modelHeader ->address = $rowData[0][2];
  $modelHeader ->academic_id = $rowData[0][3];
  $modelHeader ->mother_name = $rowData[0][4];
  $modelHeader ->father_Name = $rowData[0][5];
  $modelHeader ->gender = $rowData[0][6];
  $modelHeader ->height = $rowData[0][7];
  $modelHeader ->weight= $rowData[0][8];
  $modelHeader ->save();
}

And then the browser return an error notification like pathinfo() expects parameter 1 to be string, resource given . Please help to solve this error.

in your code you have used

 $inputFileType =\PHPExcel_IOFactory::identify($inputFiles);

which is used to identify the valid excel file and it expects the parameter as filename .

I can see in your code, you have passed $inputFiles as a parameter to identify method, which is not a file name but resource handler. and identify method expects it to be string (file name).

This is the reason you are getting error.

Note : fopen() returns a file pointer resource on success, or FALSE on error.

    $inputFiles = fopen("../file/" . $modelFile->file, "r");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM