PHP는 Excel 그림 개체를 읽고 이를 상대 경로로 저장합니다.

藏色散人
풀어 주다: 2023-04-09 17:40:01
앞으로
3449명이 탐색했습니다.
입니다. 도움이 필요한 친구들에게 도움이 되길 바랍니다!

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 = &#39;/images&#39;;

    /**
     * @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(&#39;Xlsx&#39;);
        $this->spreadsheet = $reader->load($excel_file);

        $config = [&#39;path&#39; => 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(&#39;YmdHis&#39;) . &#39;.xlsx&#39;;
        $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, &#39;/&#39;) . "{$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 .= &#39;.&#39; . $drawing->getExtension();
        switch ($drawing->getExtension()) {
            case &#39;jpg&#39;:
            case &#39;jpeg&#39;:
                $source = imagecreatefromjpeg($drawing->getPath());
                imagejpeg($source, $this->image_path . $image_filename);
                break;
            case &#39;gif&#39;:
                $source = imagecreatefromgif($drawing->getPath());
                imagegif($source, $this->image_path . $image_filename);
                break;
            case &#39;png&#39;:
                $source = imagecreatefrompng($drawing->getPath());
                imagepng($source, $this->image_path . $image_filename);
                break;
            default:
                throw new Exception(&#39;image format error!&#39;);
        }

        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 그림 개체를 읽고 이를 상대 경로로 저장합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:learnku.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!