thinkphp5 导入含图片的 excel表格

将某一列是图片的excel 导入到后台,存到数据,图片保存图片地址。

首先肯定是上传文件,然后获取该文件,进行处理后插入数据到数据库。

上传就不用说了,直接从获取文件开始:

引入处理excel 的类

use PhpOfficePhpSpreadsheetReaderXls;

获取到文件地址

           $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 就会发现 图片那一栏的值都变成了 图片所在的地址。后面就直接整理数据插入数据库。

原文地址:https://www.cnblogs.com/myIvan/p/11431248.html