zoukankan      html  css  js  c++  java
  • laraveladmin 自定义导出表单

    官方导出文档

    laravel-admin自带的导出excel会导出与此模型关联的其他数据。所以参考官方文档调整代码

    文章表:id,title,user_id

    用户表:id,username

    //文章模型关联用户
        public function user(){
            return $this->belongsTo(User::class, 'user_id', 'id');
        }
    
     
    //ExcelExporter.php
    <?php
    namespace App\Admin\Extensions;
    
    use Encore\Admin\Grid;
    use Encore\Admin\Grid\Exporters\AbstractExporter;
    use Maatwebsite\Excel\Facades\Excel;
    
    class ExcelExpoter extends AbstractExporter
    {
        protected $head = [];
        protected $body = [];
        public function setAttr($head, $body){
            $this->head = $head;
            $this->body = $body;
        }
    
        public function export()
        {
            Excel::create('Filename', function($excel) {
                $excel->sheet('Sheetname', function($sheet) {
                    // 这段逻辑是从表格数据中取出需要导出的字段
                    $head = $this->head;
                    $body = $this->body;
                    $bodyRows = collect($this->getData())->map(function ($item)use($body) {
                        foreach ($body as $keyName){
                            $arr[] = array_get($item, $keyName);
                        }
                        return $arr;
                    });
                    $rows = collect([$head])->merge($bodyRows);
                    $sheet->rows($rows);
                });
            })->export('xls');
        }
    }

    使用方法:

                $excel = new ExcelExpoter();
                $excel->setAttr(['id', '标题', '作者'], ['id', 'title', 'user.username']);
                $grid->exporter($excel);
  • 相关阅读:
    loj 1251(2-sat + 输出一组可行解)
    hdu 4751(dfs染色)
    hdu 2545(并查集求节点到根节点的距离)
    uva 10972(边双连通分量)
    uva 10246(最短路变形)
    uva 11380(最大流+拆点)
    hdu 4640(状压dp)
    hdu 1430+hdu 3567(预处理)
    python基础知识回顾[1]
    基于websocket搭建简易群聊
  • 原文地址:https://www.cnblogs.com/lxwphp/p/15453856.html
Copyright © 2011-2022 走看看