將某一列是圖片的excel 導入到後臺,存到數據,圖片保存圖片地址。數據庫
首先確定是上傳文件,而後獲取該文件,進行處理後插入數據到數據庫。數組
上傳就不用說了,直接從獲取文件開始:dom
引入處理excel 的類函數
use PhpOffice\PhpSpreadsheet\Reader\Xls;
獲取到文件地址ui
$file = '/uploads/201908/13355zz.xls'’; if (!$file) { $this->error(__('Parameter %s can not be empty', 'file')); } $inputFileName = ROOT_PATH . DS . 'public' . DS . $file; if (!is_file($inputFileName)) { $this->error(__('No results were found')); } //實例化reader $ext = pathinfo($inputFileName, PATHINFO_EXTENSION); if (!in_array($ext, ['xls'])) { $this->error(__('Unknown data format')); } $reader = new Xls(); // 讀取excel文件 try { if (!$PHPExcel = $reader->load($inputFileName)) { $this->error(__('Unknown data format')); } $sheet = $PHPExcel->getSheet(0); } catch(Exception $e) { die('加載文件發生錯誤:"'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage()); }
從excel文件裏讀取數據,圖片單獨處理(進行上傳保存)this
$data=$sheet->toArray();//該方法讀取不到圖片 圖片需單獨處理 /*************圖片單獨處理開始*****************/ $imageFilePath=ROOT_PATH.'/public/uploads/images/' ;//圖片保存目錄 if (!file_exists ( $imageFilePath )) { mkdir("$imageFilePath", 0777, true); } //處理圖片 foreach($sheet->getDrawingCollection() as $img) { list($startColumn,$startRow)= PHPExcel_Cell::coordinateFromString($img->getCoordinates());//獲取圖片所在行和列 $imageFileName = Random::uuid();//圖片名字隨機生成,若是你沒這個類,本身用其餘隨機函數生成 switch($img->getMimeType()) { case 'image/jpg': case 'image/jpeg': $imageFileName.='.jpg'; imagejpeg($img->getImageResource(),$imageFilePath.$imageFileName); break; case 'image/gif': $imageFileName.='.gif'; imagegif($img->getImageResource(),$imageFilePath.$imageFileName); break; case 'image/png': $imageFileName.='.png'; imagepng($img->getImageResource(),$imageFilePath.$imageFileName); break; } $startColumn = ABC2decimal($startColumn);//因爲圖片所在位置的列號爲字母,轉化爲數字 $data[$startRow-1][$startColumn]='/uploads/images/'.$imageFileName;//把圖片插入到數組中 } /*************圖片單獨處理結束*****************/
而後打印$data 就會發現 圖片那一欄的值都變成了 圖片所在的地址。後面就直接整理數據插入數據庫。spa