PHP利用PhpSpreadsheet 和 xlswriter 讀取Excel圖片物件,儲存替換為相對路徑
<?php
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;
class ExcelImagePathServer
{
protected $relative_path = '/images';
protected $spreadsheet;
protected $xls_writer;
protected $sheet_writer;
protected $image_path;
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);
}
}
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;
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結