php 讀取execl圖片並儲存
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
class Spreadsheet extends Command
{
protected $signature = 'spreadsheet:read {path}';
protected $description = 'phpSpreadsheet 讀取圖片並儲存';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$date = date('YmdHis');
$imageFilePath = public_path("imports/{$date}/");
if (!file_exists($imageFilePath)) {
mkdir($imageFilePath, 0755, true);
}
try {
$inputFileName = $this->argument('path');
$reader = IOFactory::createReader('Xlsx');
$objSpreadsheet = $reader->load($inputFileName);
$sheetCount = $objSpreadsheet->getSheetCount();
for ($i = 0; $i < $sheetCount; $i++) {
$worksheet = $objSpreadsheet->getSheet($i);
$data = $worksheet->toArray();
$sheetNames = $objSpreadsheet->getSheetNames();
foreach ($worksheet->getDrawingCollection() as $drawing) {
list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
$imageFileName = $sheetNames[$i] .'-'.$drawing->getCoordinates();
switch ($drawing->getExtension()) {
case 'jpg':
case 'jpeg':
$imageFileName .= '.jpg';
$source = imagecreatefromjpeg($drawing->getPath());
imagejpeg($source, $imageFilePath . $imageFileName);
break;
case 'gif':
$imageFileName .= '.gif';
$source = imagecreatefromgif($drawing->getPath());
imagegif($source, $imageFilePath . $imageFileName);
break;
case 'png':
$imageFileName .= '.png';
$source = imagecreatefrompng($drawing->getPath());
imagepng($source, $imageFilePath . $imageFileName);
break;
}
$startColumn = $this->ABC2decimal($startColumn);
dump($imageFilePath . $imageFileName);
$data[$startRow - 1][$startColumn] = $imageFilePath . $imageFileName;
}
dump(count($data));
}
} catch (\Exception $e) {
throw $e;
}
}
public 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 協議》,轉載必須註明作者和本文連結