


PHP reads the Excel picture object and saves it with a relative path
The following column PHP Tutorial will introduce to you the method of reading Excel image objects in PHP and saving and replacing them with relative paths. I hope it will be helpful to friends in need!
PHP uses PhpSpreadsheet and xlswriter to read Excel picture objects, save and replace them with relative paths
<?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; } }
The above is the detailed content of PHP reads the Excel picture object and saves it with a relative path. For more information, please follow other related articles on the PHP Chinese website!

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
