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

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

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

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/1/11 0011
 * Time: 8:59
 */

namespace App\\Services;

use PhpOffice\\PhpSpreadsheet\\Cell\\Coordinate;
use PhpOffice\\PhpSpreadsheet\\Exception;
use PhpOffice\\PhpSpreadsheet\\IOFactory;
use PhpOffice\\PhpSpreadsheet\\Spreadsheet;
use PhpOffice\\PhpSpreadsheet\\Worksheet\\Drawing;
use Vtiful\\Kernel\\Excel;

/**
 * 读取Excel图片并保存其路径
 * Class ExcelImagePathServer
 * @package App\\Services
 */
class ExcelImagePathServer
{
    /**
     * @var string
     */
    protected $relative_path = '/images';

    /**
     * @var Spreadsheet
     */
    protected $spreadsheet;

    /**
     * @var Excel
     */
    protected $xls_writer;

    /**
     * @var Excel
     */
    protected $sheet_writer;

    /**
     * @var string
     */
    protected $image_path;

    /**
     * ExcelImagePathServer constructor.
     * @param string $excel_file
     * @throws \\PhpOffice\\PhpSpreadsheet\\Reader\\Exception
     */
    public function __construct($excel_file)
    {
        $reader = IOFactory::createReader('Xlsx');
        $this->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);
        }
    }

    /**
     * @throws Exception
     */
    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) {
                /**@var $drawing 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);
    }

    /**
     * 保存图片
     *
     * @param Drawing $drawing
     * @param $image_filename
     * @return string
     * @throws Exception
     */
    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();
    }

    /**
     * 坐标转换
     *
     * @param $abc
     * @return float|int
     */
    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图片对象,并保存替换为相对路径的文章就分享到这,如果对你有帮助欢迎继续关注我们哦

本文来自投稿,不代表重蔚自留地立场,如若转载,请注明出处https://www.cwhello.com/44688.html

如有侵犯您的合法权益请发邮件951076433@qq.com联系删除

(0)
php学习php学习订阅用户
上一篇 2022年6月27日 00:30
下一篇 2022年6月27日 00:30

相关推荐

  • PHP连接MySQL数据库操作实现

    方法一:普通方法(面向过程)首先,先做出如下假设(也适用与方法二和方法三) $username=your_name; $userpass=your_pass; $dbhost=localhost; $dbdatabase=your_database;下面是关键步骤://生成一个连接 $db_co…

    2022年6月18日
    0129
  • 我来说说如何使用PHP代码实现QQ代码。

    PHP代码实现QQ代码:通过调用腾讯QQ互联API,获取access_token和openid,然后生成QQ二维码。 什么是QQ代码? QQ代码,又称为QQ透明皮肤,是一种基于腾讯QQ聊天软件的自定义皮肤,通过编写特定的HTML、CSS和JavaScript…

    2024年7月7日
    01
  • 如何使用PHP和Elasticsearch构建全文搜索引擎。

    如何使用PHP和Elasticsearch构建全文搜索引擎全文搜索引擎在现代互联网中扮演着重要的角色,它能够让用户快速找到满足他们需求的信息。一个好的全文搜索引擎不仅需要快速搜索,同时还需要提供高质量的搜索结果。这…

    2023年5月30日
    06
  • 实现基于PHP的强大Web应用。

    作为一种流行的后端编程语言,PHP已经被广泛地应用于各类Web应用的开发中。其优点在于其开放性、易用性和强大的生态系统,使得PHP成为了许多开发者的首选。但是,要想实现一款强大的Web应用,仅凭PHP作为编程语言可…

    2023年5月30日
    02
  • PHP8中的新函数:fdiv()的新应用方法。

    随着一次又一次的更新,PHP已经成为了web应用程序开发中最流行的语言之一。在过去的几年中,PHP的变化非常迅速。特别是最近发布的PHP8版本中添加了许多新特性和函数,这些新特性和函数将使PHP的应用更加强大和高效…

    2023年5月21日
    07
  • php实现定时任务教程(附代码)

    php是怎么做定时任务? 如下图所示: 具体代码如下: header("Content-type:text/html;Charset=utf8"); //原理:通过sleep一段时间后再访问脚本自身的方式继续执行 //设置sleep时间 $time=15; //获取请求的Url $url="ht…

    2018年3月29日
    0334
  • PHP入门指南:PHP和Cobol。

    PHP和Cobol是两种非常不同的编程语言,但它们都有着自己的优势和适用范围。本文将深入探讨PHP和Cobol的区别和相似之处,并为初学者提供一份PHP入门指南。PHP是一种开源的脚本语言,通常用于Web开发。它可以嵌入HTML…

    2023年5月22日
    03
  • 通过PHP实现稳定高效的直播功能。

    随着互联网技术的发展,直播已经成为了一种非常受欢迎的娱乐方式,不仅可以满足人们的娱乐需求,还能够实现商业营销和教育培训等多种用途。如果实现稳定高效的直播功能,就需要依靠一定的技术支持。在众多直播技术…

    2023年5月23日
    00

联系我们

QQ:951076433

在线咨询:点击这里给我发消息邮件:951076433@qq.com工作时间:周一至周五,9:30-18:30,节假日休息