Dcat admin 使用maatwebsite/excel3.1自定义导出

由于Dcat admin暂不支持 maatwebsite/excel3.1 对原本的导出组件进行自定义,因此使用$grid->tool()自定义按钮做导出。

Dcat admin使用maatwebsite/excel2.1进行自定义导出文档:https://learnku.com/docs/dcat-admin/2.x/data-export/8101#053fb9

1、使用maatwebsite/excel3.1完成导出接口,用于 TestExport 工具类

<?php

namespace App\Admin\Controllers;


use App\Admin\Extensions\TestExpoter;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;

class TestController extends Controller
{
    /**
     * 导出
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function export(Request $request)
    {
        $filename = $request->get('filename');

        $param = json_decode($request->get('param'));

        ob_end_clean();
        return Excel::download(new TestExpoter($param),$filename . '.xlsx');
    }
}

2、TestExpoter 类返回导出数据

<?php

namespace App\Admin\Extensions;


use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class TestExpoter implements FromCollection,WithHeadings
{
    private $row;
    private $data;
    private $headings;

    /**
     * TaskDataExcelExpoter constructor.
     * @param array $param 筛选条件
     * @param array $data 数据
     * @param array $headings 表头
     */
    public function __construct($param = [], $data = [], $headings = [])
    {
        //表头设定
        $headings = [[
        	'id' => 'ID',
            ...
        ]];
        $data = $this->getData($param);

        $this->headings = $headings;
        $this->data = $data;
    }

    public function headings(): array
    {
        return $this->headings;
    }

    public function collection()
    {
        return collect($this->data);
    }

    /**
     * 获取导出数据
     *
     * @param $param
     * @return mixed
     */
    private function getData($param)
    {
        $param = json_decode(json_encode($param), true);

        $note_monitor = DB::table('table_name')->get()->toArray();

        return $list;

    }
}

3、定义路由

Route::get('/export', 'TestController@export');

4、创建 TestExport 类继承 Dcat\Admin\Grid\Tools\AbstractTool

<?php

namespace App\Admin\Actions\Grid;

use Dcat\Admin\Grid\Tools\AbstractTool;
use Illuminate\Http\Request;

class TestExport extends AbstractTool
{
    /**
     * @return string
     */
    protected $title = '导出当前页';

    protected $request_param = [];
    
    protected $request_filename = '';

    /**
     * 接收参数
     */
    public function __construct($param = null, $filename = null, $title)
    {
        $this->request_param = $param;
        $this->request_filename = $filename;
        parent::__construct($title);

        $this->title = $title;
    }

    /**
     * 按钮样式定义,默认 btn btn-white waves-effect
     *
     * @var string
     */
    protected $style = 'btn btn-outline-info';

    /**
     * 按钮文本
     *
     * @return string|void
     */
    public function title()
    {
        return $this->title;
    }

    /**
     * 处理请求
     * 如果你的类中包含了此方法,则点击按钮后会自动向后端发起ajax请求,并且会通过此方法处理请求逻辑
     *
     * @param Request $request
     */
    public function handle(Request $request)
    {
        $param = $request->get('param');
        $filename = $request->get('filename');

        // 调用/export接口进行导出
        return $this->response()->download('/export?filename=' . $filename . '&param=' . json_encode($param) . '&_export_=1');
    }

    /**
     * 设置请求参数
     *
     * @return array|void
     */
    public function parameters()
    {
        return [
            'param' => $this->request_param,
            'filename' => $this->request_filename,
            'title' => $this->title,
        ];
    }

}

5、使用TestRepository 类展示列表

<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\TestRepository;
use Dcat\Admin\Grid;
use \Dcat\Admin\Http\Controllers\AdminController;

class TestController extends AdminController
{
    protected function grid()
    {
        return Grid::make(new TestRepository(), function (Grid $grid) {
            // 第一列显示id字段,并将这一列设置为可排序列
            $grid->column('id', 'ID')->sortable();
            ...
            
            // 自定义工具
            $grid->tools(function (Grid\Tools $tools) use ($grid){
                // 获取当前页数
                $currentPage = $grid->model()->getCurrentPage();
                // 获取每页显示行数
                $perPage = $grid->model()->getPerPage();

                $start = ($currentPage - 1) * $perPage;

                // 获取排序参数
                $sort = $grid->model()->getSort();

                // 获取筛选条件
                $id = $model->filter()->input('id'),

                // 获取规格选择器条件
                $gender = $model->filter()->input('_selector.gender'),

                $param = [
                    'sort'     => $sort,
                    'search'   => ['id' => $id],
                    'selector' => ['gender' => $gender]
                ];

                // 导出
                $tools->append(new TestExport($param, $this->title, '导出当前页'));

            });
            
            // 筛选
            $grid->filter(function ($filter) {
                // 设置id字段的范围查询
                $filter->equal('id', 'ID');
                ...
            });
            
            // 规格选择器
            $grid->selector(function (Grid\Tools\Selector $selector) {
                //性别
                $selector->select('gender', '性别', [0 => '男', 1 => '女', '' => '未标明']);

            });
            
        });
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
使用 dcat adminmaatwebsite/excel 导入数据的步骤如下: 1. 安装 maatwebsite/excel 依赖包,可以使用 composer 命令进行安装: ``` composer require maatwebsite/excel ``` 2. 在 dcat admin 中创建一个数据表,并在该表对应的 Model 中添加 `use Maatwebsite\Excel\Concerns\ToModel;` 和 `use Maatwebsite\Excel\Concerns\WithHeadingRow;` 引用。 3. 创建一个实现 `ToModel` 接口的类,该类负责将 Excel 中的数据转换为 Model 实例。例如: ```php <?php namespace App\Imports; use App\Models\User; use Maatwebsite\Excel\Concerns\ToModel; use Maatwebsite\Excel\Concerns\WithHeadingRow; class UsersImport implements ToModel, WithHeadingRow { public function model(array $row) { return new User([ 'name' => $row['name'], 'email' => $row['email'], 'password' => bcrypt($row['password']), ]); } } ``` 4. 在 dcat admin 中创建一个导入数据的页面,并对页面进行配置,如下所示: ```php use App\Imports\UsersImport; use Maatwebsite\Excel\Facades\Excel; // ... $form->file('import_file', '导入文件'); // ... $form->footer(function ($footer) { $footer->disableReset(); $footer->disableSubmit(); $footer->addButton('导入', [ 'class' => 'btn btn-primary', 'onclick' => <<<JS var formData = new FormData(); formData.append('import_file', $('#import_file')[0].files[0]); $.ajax({ url: '{$this->getResource()}/import', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, data: formData, type: 'POST', cache: false, contentType: false, processData: false, success: function (data) { Dcat.success(data.message); }, error: function (xhr, textStatus, errorThrown) { Dcat.error(xhr.responseJSON.message || '操作失败'); } }); JS, ]); }); ``` 5. 在控制器中添加导入数据的方法: ```php public function import(Request $request) { $file = $request->file('import_file'); Excel::import(new UsersImport, $file); return response()->json([ 'message' => '导入成功', ]); } ``` 以上就是使用 dcat adminmaatwebsite/excel 导入数据的基本步骤。需要注意的是,以上代码仅作为参考,具体实现可能会有所不同,具体实现应根据实际情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值