thinkphp5 導入含圖片的 excel表格


將某一列是圖片的excel 導入到后台,存到數據,圖片保存圖片地址。

首先肯定是上傳文件,然后獲取該文件,進行處理后插入數據到數據庫。

上傳就不用說了,直接從獲取文件開始:

引入處理excel 的類

use PhpOffice\PhpSpreadsheet\Reader\Xls;

獲取到文件地址

           $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文件里讀取數據,圖片單獨處理(進行上傳保存)

           $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 就會發現 圖片那一欄的值都變成了 圖片所在的地址。后面就直接整理數據插入數據庫。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM