利用php實現讀取excel中的圖片

2020-07-16 10:06:05

要實現讀取excel中的圖片,可以通過phpspreadsheet來實現。phpspreadsheet是一個純php編寫的庫,並引入了名稱空間、PSR規範等。

使用composer安裝phpspreadsheet

composer require phpoffice/phpspreadsheet

GitHub下載:

https://github.com/PHPOffice/PhpSpreadsheet

(免費視訊教學推薦:php視訊教學

excel圖片如下圖:

7ead23da258f75fdf3cbfce2f8b7bd8.png

專案範例:

use PhpOfficePhpSpreadsheetCellCoordinate;
use PhpOfficePhpSpreadsheetIOFactory;
$imageFilePath = './uploads/imgs/'; //圖片本地儲存的路徑
if (!file_exists($imageFilePath)) { //如果目錄不存在則遞回建立
 mkdir($imageFilePath, 0777, true);
}
try {
 $inputFileName = './files/1.xlsx'; //包含圖片的Excel檔案
 $objRead = IOFactory::createReader('Xlsx');
 $objSpreadsheet = $objRead->load($inputFileName);
 $objWorksheet = $objSpreadsheet->getSheet(0);
 $data = $objWorksheet->toArray();
 foreach ($objWorksheet->getDrawingCollection() as $drawing) {
  list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
  $imageFileName = $drawing->getCoordinates() . mt_rand(1000, 9999);
  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 = ABC2decimal($startColumn);
  $data[$startRow-1][$startColumn] = $imageFilePath . $imageFileName;
 }
 dump($data);die();
} 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;
}

結果如圖:

3c6886e3cc2e015c0187f01ea9bbde7.png

以上就是利用php實現讀取excel中的圖片的詳細內容,更多請關注TW511.COM其它相關文章!