TP6框架--EasyAdmin學習筆記:excel的數據,圖片處理

這是我寫的學習EasyAdmin的第七章,這一章我給你們分享下如何處理excel中的數據,圖片

原理就是使用easyadmin中封裝好的phpexcel,來進行數據的導入,view層咱們須要一個用了導入excel的頁面,代碼以下:

<div class="layuimini-container">
    <form id="app-form" class="layui-form layuimini-form">
        <div class="layui-form-item">
            <label class="layui-form-label">導入excel:</label>
            <div class="layui-input-block">
               <button type="button" class="layui-btn" id="test1">
                  <i class="layui-icon"></i>上傳文件
                </button>
            </div>
        </div>
    </form>
</div>
<script src="/static/plugs/layui-v2.5.6/layui.all.js?v=2.0.0" charset="utf-8"></script>
<script src="/static/plugs/jquery-3.4.1/jquery-3.4.1.min.js?v=2.0.0" charset="utf-8"></script>
<script>
layui.use('upload', function(){
  var upload = layui.upload;
  var loading;
  //執行實例
  var uploadInst = upload.render({
    elem: '#test1' //綁定元素
    ,url: '/admin/mall.goodsone/import' //上傳接口
    ,accept: 'file'
    ,choose:function(){
        loading = layer.load(0, {
            shade: false,
            time: 60*60*1000
        });
    }
    ,done: function(res){
      //上傳完畢回調
      layer.close(loading);
      if(res.msg == '導入成功'){
        layer.msg(res.msg); 
      }
    }
    ,error: function(){
        layer.close(loading);
      //請求異常回調

    }
  });
});

</script>

js中加入如下代碼:

 接下來就是重點,controller部分的代碼,這裏先在前面導入easyadmin封裝好的phpexcel

use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;

在方法裏寫入下面代碼

            $file = request()->file('file');
            ini_set('memory_limit','1024M');
            $data =  Excel::import($file);        

$data裏就是處理好的數據數組,可是實際用的時候會發現,圖片無法識別,這裏給出解決方法,親測有用,你們能夠照着思路來就行

PHPSpreadsheet

首先安裝phpspreadsheet,因爲線上服務器PHP版本是PHP5.6,因此須要安裝兼容PHP5.6的版本,這裏安裝1.8.2版本

composer require phpoffice/phpspreadsheet=1.8.2

而後就能夠在項目裏使用了

use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;

$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;
}

能夠看到,圖片被讀取並存到了本地服務器中

PHPExcel

PHPExcel實現從Excel文件裏讀取內容的方法和phpspreadsheet幾乎同樣,畢竟phpspreadsheet就是在PHPExcel基礎上寫的,不過PHPExcel因爲已經被廢棄了,因此建議優先使用phpspreadsheet,若是原來項目裏一直使用了PHPExcel也能夠繼續使用PHPExcel的方法

use PHPExcel_IOFactory;
use PHPExcel_Cell;

try {
    $inputFileName = './files/1.xlsx';
    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    $objPHPExcel = $objReader->load($inputFileName);
} catch (\Exception $e) {
    die('加載文件發生錯誤:"'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}

$sheet = $objPHPExcel->getSheet(0);
$data = $sheet->toArray(); //該方法讀取不到圖片,圖片需單獨處理
$imageFilePath = './uploads/imgs/'; //圖片本地存儲的路徑
if (!file_exists($imageFilePath)) {
    mkdir($imageFilePath, 0777, true);
}

//處理圖片
foreach ($sheet->getDrawingCollection() as $img) {
    list($startColumn, $startRow) = PHPExcel_Cell::coordinateFromString($img->getCoordinates()); //獲取圖片所在行和列
    $imageFileName = $img->getCoordinates() . mt_rand(1000, 9999);
    switch($img->getExtension()) {
        case 'jpg':
        case 'jpeg':
            $imageFileName .= '.jpeg';
            $source = imagecreatefromjpeg($img->getPath());
            imagejpeg($source, $imageFilePath.$imageFileName);
            break;
        case 'gif':
            $imageFileName .= '.gif';
            $source = imagecreatefromgif($img->getPath());
            imagejpeg($source, $imageFilePath.$imageFileName);
            break;
        case 'png':
            $imageFileName .= '.png';
            $source = imagecreatefrompng($img->getPath());
            imagejpeg($source, $imageFilePath.$imageFileName);
            break;
    }
    $startColumn = ABC2decimal($startColumn);
    $data[$startRow-1][$startColumn] = $imageFilePath . $imageFileName;

}
var_dump($data);

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;
}

這部分思路我參考於https://www.cnblogs.com/itbsl/p/11883458.html

若是本文對你有所幫助,麻煩你點個贊。

相關文章
相關標籤/搜索