laravel-admin 自定义列表导出

新建一个导出类继承AbstractExporter,添加下列方法

public function setAttr($head, $body, $filename, $sheetname = null){
    $this->head = $head;
    $this->body = $body;
    $this->filename = $filename;
    $this->sheetname = $sheetname;
}

public function export()
{
    Excel::create($this->filename, function($excel) {
        $excel->sheet($this->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');
}

在列表方法grid()中加入

$excel = new ExcelExpoter();

$excel->setAttr( ['等级','商品ID', ...], ['level_id','goods_id', ...] ,'商品分配模板','商品');

$grid->exporter($excel);

赵鹏磊

hello world

云端