Dcat Admin实现简单的excel导入功能

Dcat Admin
Dcat Admin是一个基于laravel-admin二次开发而成的后台系统构建工具,只需极少的代码即可快速构建出一个功能完善的高颜值后台系统。支持页面一键生成CURD代码,内置丰富的后台常用组件,开箱即用,让开发者告别冗杂的HTML代码,对后端开发者非常友好。
参考链接:blog.csdn.net/qq_42468039/article/...
本次实现的导入功能是Dcat的版本为”dcat/laravel-admin”: “2.0.9-beta”,
实现效果

Dcat-admin实现简单的excel导入功能

Dcat-admin实现简单的excel导入功能
1.安装maatwebsite/excel

composer require maatwebsite/excel

2.在控制器中添加按钮

use App\Admin\Actions\Modal\memberModal;
$grid->tools(function  (Grid\Tools  $tools)  { 
    //Excel导入
    $tools->append(new  memberModal());  
});

3.创建文件

Dcat-admin实现简单的excel导入功能

app/admin/actions/Modal/memberModal.php

<?php

namespace App\Admin\Actions\Modal;

use App\Admin\Actions\Form\memberForm;
use Dcat\Admin\Admin;
use Dcat\Admin\Grid\Tools\AbstractTool;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;


class memberModal extends AbstractTool
{
    /**
     * @return string
     */
    protected $title = 'Title';

    public function render()
    {
        $id = "reset-pwd-{$this->getKey()}";

        // 模态窗
        $this->modal($id);

        return <<<HTML
<span class="grid-expand" data-toggle="modal" data-target="#{$id}">
   <a href="javascript:void(0)"><button class="btn btn-outline-info ">上传Excel并导入数据</button></a>
</span>
HTML;
    }

    protected function modal($id)
    {
        $form = new memberForm();

        Admin::script('Dcat.onPjaxComplete(function () {
            $(".modal-backdrop").remove();
            $("body").removeClass("modal-open");
        }, true)');

        // 通过 Admin::html 方法设置模态窗HTML
        Admin::html(
            <<<HTML
<div class="modal fade" id="{$id}">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">导入数据</h4>
         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
        {$form->render()}
      </div>
    </div>
  </div>
</div>
HTML
        );
    }

    /**
     * @param Model|Authenticatable|HasPermissions|null $user
     *
     * @return bool
     */
    protected function authorize($user): bool
    {
        return true;
    }

    /**
     * @return array
     */
    protected function parameters()
    {
        return [];
    }
}

app/admin/actions/Form/memberForm.php

<?php

namespace App\Admin\Actions\Form;

use App\Admin\Actions\Imports\memberImport;
use Dcat\Admin\Widgets\Form;
use Maatwebsite\Excel\Facades\Excel;

class memberForm extends Form
{
    public function handle(array $input)
    {
        try {
            //上传文件位置,这里默认是在storage中,如有修改请对应替换
            $file = storage_path('/app/public/' . $input['file']);
            Excel::import(new memberImport(), $file);
            return $this->response()->success('数据导入成功')->refresh();
        } catch (\Exception $e) {
            return $this->response()->error($e->getMessage());
        }
    }

    public function form()
    {
        $this->file('file', '上传数据(Excel)')->rules('required', ['required' => '文件不能为空'])->move('admin/upload/');

    }

}

app/admin/actions/Imports/memberImport.php

<?php

namespace App\Admin\Actions\Imports;

use App\Models\Member;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;

class memberImport implements ToModel, WithStartRow
{
    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function model(array $row)
    {
        // 0代表的是第一列 以此类推
        // $row 是每一行的数据
        //查询是否存在,存在就不写入
        $user = Member::where('username', '=', $row[0])->first();
        if ($user) {
            return null;
        }
        return new Member([
            'username' => $row[0],
            'name' => $row[1],
        ]);

    }


    /**
     * 从第几行开始处理数据 就是不处理标题
     * @return int
     */
    public function startRow(): int
    {
        return 2;
    }
}

4.Model允许写入

class Member extends Model
{
  protected $fillable = ['name','username'];
}

5.导入Excel样式
Dcat-admin实现简单的excel导入功能

本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由 MArtian 于 2年前 加精
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 10

写的很详细,谢谢 :+1:

2年前 评论

file

2年前 评论
erdongchen 2年前

Field [response] does not exist. 这个怎么解决一下,说用命令行创建form,但是创建的form是类似modal的内容

2年前 评论
TigerLin 2年前

图片中的重置按钮没有被使用 请问怎么消失或者是做事件

1年前 评论

使用这个版主的方式,可以成功导入2千条左右数据,数据量比较多起来就会报错, 求助怎么解决呢?谢谢 我一次性导入不到5千条数据,报错如下 exception: "Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException" file:"我的项目路径\vendor\laravel\framework\src\Illuminate\Routing\AbstractRouteCollection.php" line: 117 message: "The GET method is not supported for this route. Supported methods: POST."

1年前 评论

想请教一下,我添加了两个导入按钮,第二个打开后还是第一个是什么原因呢

1年前 评论

ToModel和WithStartRow 这两个呢

1个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!