栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

PHP读取Excel图片对象,并保存替换为相对路径

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PHP读取Excel图片对象,并保存替换为相对路径

下面由PHP教程栏目给大家介绍PHP读取Excel图片对象,并保存替换为相对路径方法,希望对需要的朋友有所帮助!

PHP利用PhpSpreadsheet 和 xlswriter 读取Excel图片对象,保存替换为相对路径

spreadsheet = $reader->load($excel_file);

 $config = ['path' => dirname($excel_file)];
 $this->xls_writer = new Excel($config);

 $this->image_path = dirname($excel_file) . $this->relative_path;
 if (!is_dir($this->image_path)) {
     mkdir($this->image_path, 0755);
 }
    }

    
    public function handle()
    {
 $write_filename = date('YmdHis') . '.xlsx';
 $sheetCount = $this->spreadsheet->getSheetCount();
 for ($i = 0; $i < $sheetCount; $i++) {
     $worksheet = $this->spreadsheet->getSheet($i);
     $data = $worksheet->toArray();
     $sheetNames = $this->spreadsheet->getSheetNames();
     var_dump($sheetCount, $sheetNames);
     // 读取并修改
     foreach ($worksheet->getDrawingCollection() as $drawing) {
  
  list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
  $image_filename = "/{$i}-" . $drawing->getCoordinates();
  $image_suffix = $this->saveImage($drawing, $image_filename);
  $image_name = ltrim($this->relative_path, '/') . "{$image_filename}.{$image_suffix}";
  var_dump($image_name);
  $startColumn = $this->ABC2decimal($startColumn);

  $data[$startRow - 1][$startColumn] = $image_name;
     }

     // 写入文件
     if ($i == 0) {
  $this->sheet_writer = $this->xls_writer->fileName($write_filename, $sheetNames[$i])->data($data);
     } else {
  // 向文件中追加工作表
  $this->sheet_writer->addSheet($sheetNames[$i])->data($data);
     }
 }
 // 最后的最后,输出文件
 $filePath = $this->sheet_writer->output();
 var_dump($filePath);
    }

    
    protected function saveImage(Drawing $drawing, $image_filename)
    {
 $image_filename .= '.' . $drawing->getExtension();
 switch ($drawing->getExtension()) {
     case 'jpg':
     case 'jpeg':
  $source = imagecreatefromjpeg($drawing->getPath());
  imagejpeg($source, $this->image_path . $image_filename);
  break;
     case 'gif':
  $source = imagecreatefromgif($drawing->getPath());
  imagegif($source, $this->image_path . $image_filename);
  break;
     case 'png':
  $source = imagecreatefrompng($drawing->getPath());
  imagepng($source, $this->image_path . $image_filename);
  break;
     default:
  throw new Exception('image format error!');
 }

 return $drawing->getExtension();
    }

    
    protected function ABC2decimal($abc)
    {
 $ten = 0;
 $len = strlen($abc);
 for ($i = 1; $i <= $len; $i++) {
     $char = substr($abc, 0 - $i, 1);//反向获取单个字符

     $int = ord($char);
     $ten += ($int - 65) * pow(26, $i - 1);
 }
 return $ten;
    }
}

以上就是PHP读取Excel图片对象,并保存替换为相对路径的详细内容,更多请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/262623.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号