phpSpreadsheet Artisan command 读取图片并另存为文件
php 读取execl图片并保存
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
class Spreadsheet extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'spreadsheet:read {path}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'phpSpreadsheet 读取图片并保存';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*/
public function handle()
{
//图片本地存储的路径
$date = date('YmdHis');
$imageFilePath = public_path("imports/{$date}/");
//如果目录不存在则递归创建
if (!file_exists($imageFilePath)) {
mkdir($imageFilePath, 0755, true);
}
try {
//包含图片的Excel文件
$inputFileName = $this->argument('path');
$reader = IOFactory::createReader('Xlsx');
$objSpreadsheet = $reader->load($inputFileName);
$sheetCount = $objSpreadsheet->getSheetCount();
// $objWorksheet = $objSpreadsheet->getSheet(0);
for ($i = 0; $i < $sheetCount; $i++) {
$worksheet = $objSpreadsheet->getSheet($i);
$data = $worksheet->toArray();
$sheetNames = $objSpreadsheet->getSheetNames();
//dump($sheetCount);
//dump($data);
foreach ($worksheet->getDrawingCollection() as $drawing) {
/**@var $drawing \PhpOffice\PhpSpreadsheet\Worksheet\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 协议》,转载必须注明作者和本文链接
推荐文章: