laravel 5.5 使用”maatwebsite/excel”: “^3.1” 简易导出excel

laravel框架学习

本例是使用导出员工的

安装部分就不说了

安装完成后在Exports文件夹中创建一个模型,

<?php

namespace App\Exports;

use App\Models\Api\Employee;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
class EmployeesExport implements FromCollection,WithHeadings
{
    use Exportable;

    private $data;
    private $headings;
    /**
    * @return \Illuminate\Support\Collection
    */
    //数据注入
    public function __construct($data, $headings)
    {
        $this->data = $data;
        $this->headings = $headings;
    }

    //实现FromCollection接口
    public function collection()
    {
        return collect($this->data);
    }

    //实现WithHeadings接口
    public function headings():array
    {
        return $this->headings;
    }
}

 

然后在控制器中引入模型

use Excel;
use App\Exports\EmployeesExport;

在使用
//$DB_Query->with('progress.progress');
        $data = $DB_Query->orderByRaw($this->order_by)->get();
        $all_qualification = $this->all_qualification();
        $all_from  = $this->all_from();
        $all_profess = $this->all_profess();
        if (empty($data)){
            errorEcho('参数错误');
        }else{
            $cell_data = array();
            $i = 0;
            foreach ($data as $item){
                $cell_data[$i]['name'] = $item['name'];
                $cell_data[$i]['tel'] = $item['tel'];
                $cell_data[$i]['qualification'] = $all_qualification[$item['qualification']];
                $cell_data[$i]['rank'] = $item['rank'].'星';
                $cell_data[$i]['from'] = $all_from[$item['from']];
                $cell_data[$i]['follower'] = $item['follower'];
                $cell_data[$i]['progressing'] = $all_profess[$item['progressing']];
                $i++;
            }
        }

            $headings = [
                '姓名',
                '电话',
                '职称',
                '人员星级',
                '简历渠道',
                '跟进人',
                '目前进度'

            ];
            return Excel::download(new EmployeesExport($cell_data, $headings), '人员管理-'.date("Y-m-d",time()).'.xls');

 

 

白发渔樵

白发渔樵

发表评论

电子邮件地址不会被公开。 必填项已用*标注