利用php实现读取excel中的图片

要实现读取excel中的图片,可以通过phpspreadsheet来实现。phpspreadsheet是一个纯php编写的库,并引入了命名空间、PSR规范等。

使用composer安装phpspreadsheet

composer require phpoffice/phpspreadsheet

GitHub下载:

https://github.com/PHPOffice/PhpSpreadsheet

excel图片如下图:

7ead23da258f75fdf3cbfce2f8b7bd8.png

项目实例:

  1. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  2. use PhpOffice\PhpSpreadsheet\IOFactory;
  3. $imageFilePath = './uploads/imgs/'; //图片本地存储的路径
  4. if (!file_exists($imageFilePath)) { //如果目录不存在则递归创建
  5. mkdir($imageFilePath, 0777, true);
  6. }
  7. try {
  8. $inputFileName = './files/1.xlsx'; //包含图片的Excel文件
  9. $objRead = IOFactory::createReader('Xlsx');
  10. $objSpreadsheet = $objRead->load($inputFileName);
  11. $objWorksheet = $objSpreadsheet->getSheet(0);
  12. $data = $objWorksheet->toArray();
  13. foreach ($objWorksheet->getDrawingCollection() as $drawing) {
  14. list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
  15. $imageFileName = $drawing->getCoordinates() . mt_rand(1000, 9999);
  16. switch ($drawing->getExtension()) {
  17. case 'jpg':
  18. case 'jpeg':
  19. $imageFileName .= '.jpg';
  20. $source = imagecreatefromjpeg($drawing->getPath());
  21. imagejpeg($source, $imageFilePath . $imageFileName);
  22. break;
  23. case 'gif':
  24. $imageFileName .= '.gif';
  25. $source = imagecreatefromgif($drawing->getPath());
  26. imagegif($source, $imageFilePath . $imageFileName);
  27. break;
  28. case 'png':
  29. $imageFileName .= '.png';
  30. $source = imagecreatefrompng($drawing->getPath());
  31. imagepng($source, $imageFilePath, $imageFileName);
  32. break;
  33. }
  34. $startColumn = ABC2decimal($startColumn);
  35. $data[$startRow-1][$startColumn] = $imageFilePath . $imageFileName;
  36. }
  37. dump($data);die();
  38. } catch (\Exception $e) {
  39. throw $e;
  40. }
  41. public function ABC2decimal($abc)
  42. {
  43. $ten = 0;
  44. $len = strlen($abc);
  45. for($i=1;$i<=$len;$i++){
  46. $char = substr($abc,0-$i,1);//反向获取单个字符
  47. $int = ord($char);
  48. $ten += ($int-65)*pow(26,$i-1);
  49. }
  50. return $ten;
  51. }

结果如图:

利用php实现读取excel中的图片