Laravel-admin 添加 Excel 导入功能

1. 引入 laravel-excel;
2. 添加导入按钮: // 导入

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

2. 导入按钮控制器:

script());
        if (Request::path() == 'loansarticles'){
            $url = 'loansnewsimport';
        }else {
            $url = 'cardnewsimport';
        }
        return view('admin.tools.excelimport')->with('url',$url);
    }
}

3. 按钮视图: \resources\views\admin\tools\excelimport.blade.php

4. 导入的方法:重组数据拼 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();
}

 

5. 写路由

6. Models 里面添加要导入的字段:  protected $fillable = ['xx','xx',...]

7. 准备表格文件 / 导入数据

Laravel-admin 添加 Excel 导入功能_第1张图片

转载:http://www.zongscan.com/demo333/174.html

————————————————
原文作者:houtizong
转自链接:https://www.zongscan.com/demo333/174.html
版权声明:著作权归作者所有。转载请保留以上作者信息和原文链接。

你可能感兴趣的:(php,项目,知识点案例)