TeacherExporter.php 9.2 KB
<?php
/**
+-----------------------------------------------------------------------------------------------------------------------
 * 扩展类:教师 excel 导出扩展类
+-----------------------------------------------------------------------------------------------------------------------
 *
 * PHP version 7
 *
 * @category  App\Admin\Extensions\Exporter
 * @package   App\Admin\Extensions\Exporter
 * @author    Richer <yangzi1028@163.com>
 * @date      2021年11月9日16:47:36
 * @copyright 2020-2022 Richer (http://www.xxxxxx.com)
 * @license   http://www.xxxxxx.com License
 * @link      http://www.xxxxxx.com
 */
namespace App\Admin\Extensions\Exporter;

use App\Admin\Rewrite\Facades\Admin;
use App\Models\SchoolClass;
use App\Models\System\SystemConfig;
use App\Models\Teacher;
use Illuminate\Support\Arr;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Facades\Excel;

/**
 * Class TeacherExporter
 *
 * @category  App\Admin\Extensions\Exporter
 * @package   App\Admin\Extensions\Exporter
 * @author    Richer <yangzi1028@163.com>
 * @date      2021年11月9日16:47:36
 * @copyright 2020-2022 Richer (http://www.xxxxxx.com)
 * @license   http://www.xxxxxx.com License
 * @link      http://www.xxxxxx.com
 */
class TeacherExporter implements FromCollection, WithEvents, WithStrictNullComparison, WithColumnFormatting
{
    // 要导出的数据
    public $data;
    // 总行数
    public $rowNum;
    public $title;
    // 导出列表
    protected $columns = [];

    /**
     * 构造函数
     *
     * ClassExporter constructor.
     * @param $excel_title
     */
    public function __construct($excel_title)
    {
        $this->columns = $this->getColumns();
        $this->title = $excel_title;
    }

    /**
     * 生效列表
     *
     * @return array
     */
    public function getColumns()
    {
        return [
            'id'        => __('No'),
            'class_id'  => __('class_name'),
            'name'  => __('teacher_name'),
            'mobile'        => __('mobile'),
            'ID_number'     => __('ID_number'),
            'gender'    => __('gender'),
            'age'       => __('age'),
            'birthday'  => __('birthday'),
            'nation'    => __('nation'),
            'graduated_school'  => __('graduated_school'),
            'operation_org' => __('operation_org'),
            'marriage'  => __('marriage'),
            'employment_type'   => __('employment_type'),
            'education'     => __('education'),
            'major'         => __('major'),
            'whether_reading'   => __('whether_reading'),
            'qualification_certificate' => __('qualification_certificate'),
            'contact_address'           => __('contact_address'),
            'entered_at'    => __('entered_at'),
            'resigned_at'   => __('resigned_at'),
            'created_at'    => __('created_at'),
        ];
    }

    /**
     * registerEvents.
     * 事件监听
     * @return array
     */
    public function registerEvents(): array
    {
        return [
            // 生成表单元后处理事件
            AfterSheet::class => function (AfterSheet $event) {
                // 定义列宽度
                $widths = [
                    'A' => 5, 'B' => 30, 'C' => 20, 'D' => 15, 'E' => 20, 'F' => 10, 'G' => 10, 'H' => 10, 'I' => 10,
                    'J' => 30, 'K' => 20, 'L' => 10, 'M' => 20, 'N' => 20, 'O' => 20, 'P' => 20, 'Q' => 50, 'R' => 50,
                    'S' => 20, 'T' => 20, 'U' => 20
                ];

                foreach ($widths as $k => $v) {
                    // 设置列宽度
                    $event->sheet->getDelegate()->getColumnDimension($k)->setWidth($v);
                }

                // 设置表头样式
                $event->sheet->getDelegate()->getStyle('A1:Y1')->applyFromArray([
                    // 设置单元格字体
                    'font' => [
                        'name'  => '宋体',
                        'bold'  => true,
                        'italic' => false,
                        'strikethrough' => false,
                        'color' => [
                            'rgb' => '000000',
                        ],
                    ],
                    // 设置单元格背景色
//                    'fill' => [
//                        'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
//                        'rotation' => 0, //渐变角度
//                        'startColor' => [
//                            'rgb' => 'FEFF00' //初始颜色
//                        ],
//                        'endColor' => [
//                            'argb' => 'FEFF00',
//                        ],
//                    ],
                ]);
            },
        ];
    }

    /**
     * collection.
     *
     * @return \Illuminate\Support\Collection
     *
     * @throws \Exception
     */
    public function collection()
    {
        $list =  Teacher::with(['class'])
            ->when($para = request('class_id', 0), function ($query) use ($para) {
                $query->where('class_id', $para);
            })
            ->when($para = request('operation_org', 0), function ($query) use ($para) {
                $query->where('operation_org', $para);
            })
            ->when($para = request('employment_type', 0), function ($query) use ($para) {
                $query->where('employment_type', $para);
            })
            ->when($para = request('entered_at', 0), function ($query) use ($para) {
                $query->whereDate('entered_at', '>=', Arr::get($para, 'start'))
                    ->whereDate('entered_at', '<=', Arr::get($para, 'end'));
            })
            ->when($para = request('resigned_at', 0), function ($query) use ($para) {
                $query->whereDate('resigned_at', '>=', Arr::get($para, 'start'))
                    ->whereDate('resigned_at', '<=', Arr::get($para, 'end'));
            })
            ->when($para = request('name', 0), function ($query) use ($para) {
                $query->where('name', 'LIKE', '%' . $para . '%');
            })
            ->when($para = request('mobile', 0), function ($query) use ($para) {
                $query->where('mobile', 'LIKE', '%' . $para . '%');
            })
            ->latest()->get();

        // 只有超管才能导出身份证号
        $user = Admin::user();
        $isAdmin = 0;
        if ($user->isAdministrator() || $user->isRole('data.manager')) {
            $isAdmin = 1;
        }
        $data = $list->map(function ($item, $index) use ($isAdmin) {
            return [
                $index+1,
                optional($item->class)->name,
                $item->name,
                "\t". $item->mobile,
                $isAdmin ? "\t". $item->ID_number : '********************' ,// 对于长数字字符串导出excel会变成科学计数,请在字符串前面加上 "\t",例如:$str = "\t" . $str;
                $item->gender_show,
                $item->age,
                $item->birthday,
                $item->nation,
                $item->graduated_school,
                SystemConfig::getSingleSelectShowValue('operation_org', $item->operation_org),
                SystemConfig::getSingleSelectShowValue('marriage', $item->marriage, SystemConfig:: getMarriedOption()),
                SystemConfig::getSingleSelectShowValue('employment_type', $item->employment_type),
                SystemConfig::getSingleSelect2TextShowValue('education', $item->education, $item->education_supplement),
                SystemConfig::getSingleSelect2TextShowValue('major', $item->major, $item->major_supplement),
                SystemConfig::getSingleSelect2SingleSelectShowValue('whether_reading', $item->whether_reading, $item->whether_reading_supplement),
                SystemConfig::getMultipleSelect2TextShowValue('qualification_certificate', $item->qualification_certificate, $item->qualification_certificate_supplement),


                $item->contact_address,
                format_date($item->entered_at, 'Y-m-d'),
                format_date($item->entered_at, 'Y-m-d'),
                format_date($item->created_at) ?? '--',
            ];
        })->toArray();

        // 设置表头
        $headings = array_values($this->columns);
        array_unshift($data, $headings);
        $this->rowNum = count($data);
        // 此处数据需要数组转集合
        return collect($data);
    }

    /**
     * @return array
     */
    public function array(): array
    {
//        dd(request()->all());

        // 取出需求导出的数据
        $userDatas = SchoolClass::get();
        foreach ($userDatas as $k => $v) {
            $data[] = [
                $v->id,
                $v->name,
                $v->gender,
                $v->age,
            ];
        }

        return $data;
    }

    /**
     * 设置列单元格格式
     */
    public function columnFormats(): array
    {
        // TODO: Implement columnFormats() method.
        return [

        ];
    }

    public function export()
    {
        return Excel::download($this, $this->title.'列表_'.date('YmdHis') . '.xlsx');
    }
}