Laravel-admin 新增 Excel 匯入功能

houtizong發表於2020-04-20

歡迎使用社群 Markdown 編輯器寫文章!

1.引入laravel-excel;
2.新增匯入按鈕:
//匯入

 $grid->tools(function ($tools) {
   $tools->append(new ExcelImport());
 });
 //匯出
 $grid->exporter(new ExcelExporter('cardnews'));

file
2.匯入按鈕控制器:

<?php
namespace App\Admin\Extensions\Tools;
use Encore\Admin\Admin;
use Encore\Admin\Grid\Tools\AbstractTool;
use Illuminate\Support\Facades\Request;

class ExcelImport extends AbstractTool
{
    public function script()
    {
        return <<<EOT
   $('.file-upload').on('change', function () {
        $('.file-upload-form').submit();
    });
EOT;
    }
    public function render()
    {
        Admin::script($this->script());
        if (Request::path() == 'loansarticles'){
            $url = 'loansnewsimport';
        }else {
            $url = 'cardnewsimport';
        }
        return view('admin.tools.excelimport')->with('url',$url);
    }
}
  1. 按鈕檢視:

    \resources\views\admin\tools\excelimport.blade.php
  2. 匯入的方法:重組資料拼sql,插入資料庫

    public function import(Request $request)
    {
      $files = $request->file('files');
      $dir = $request->get('dir', '/');
      $manager = new MediaManager($dir,'xlsx');
      try {
          //檔案上傳伺服器
          if ($manager->upload($files)) {
              admin_toastr('匯入成功');
          }
          //檔案儲存路徑
          $filePath = "/data/www/cbb_new/storage/app/public/".$files[0]->getClientOriginalName();
    
          Excel::load($filePath, function($reader) {
              $data = $reader->all();
              //dd($data);
              //批量儲存
              $value=[];
              $lastid = CardArticle::orderBy('id','desc')->limit(1)->value('id');
              foreach ($data as $k => $v ){
                  $lastid++;
                  //儲存表格每行的值
                  $value['title']    =$v['title'];
                  $value['dt'] =date('Y-m-d Hs');
                  $value['seotitle'] =$v['seotitle'];
                  $value['keywords'] =$v['keywords'];
                  $value['author']   =$v['author'];
                  $value['class_id'] = intval($v['class_id']);
                  $value['bank_id']  =intval($v['bank_id']);
                  $value['content']  =$v['content'];
                  $value['views']    =intval($v['views']);
                  $value['order']    =intval($v['order']);
                  $value['generate_url']=  '/cardnews/cardnews_'.$lastid.'.shtml';
                  $value['status']   =intval($v['status']);
    
                  CardArticle::create($value);
              }
          });
    
      } catch (\Exception $e) {
          admin_toastr($e->getMessage(), 'error');
      }
      return back();
    }
  3. 寫路由

  4. 準備表格檔案/匯入資料
    file
    file

轉載

laravel-admin 新增Excel匯入功能

本作品採用《CC 協議》,轉載必須註明作者和本文連結

個人部落格:www.zongscan.com

相關文章