ClassExporter.php 11.7 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\Models\SchoolClass;
use App\Models\System\SystemConfig;
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 ClassExporter
 *
 * @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 ClassExporter 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'),
            'province_id'   => __('province'),
            'city_id'       => __('city'),
            'county_id'     => __('county'),
            'township_id'   => __('township'),
            'village_id'    => __('village'),
            'group_id'      => __('group'),
            'name'        => __('class_name'),
            'class_started_at'  => __('class_started_at'),
            'class_closed_at'   => __('class_closed_at'),
            'belonged_org'  => __('belonged_org'),
            'operation_org' => __('operation_org'),
            'class_sponsor' => __('class_sponsor'),
            'class_mode'        => __('class_mode'),
            'class_type'        => __('class_type'),
            'class_location'    => __('class_location'),
            'class_policy'      => __('class_policy'),
            'class_service_hours'   => __('class_service_hours'),
            'whether_nap'           => __('whether_nap'),
            'whether_lunch'         => __('whether_lunch'),
            'outdoor_play_facilities'   => __('outdoor_play_facilities'),
            'indoor_play_facilities'    => __('indoor_play_facilities'),
            'family_committee'          => __('family_committee'),
            'other'                     => __('other'),
            'student_number'     => __('student_number'),
            'boy_number' => __('boy_number'),
            'girl_number'  => __('girl_number'),
            'han_nationality_number'  => __('han_nationality_number'),
            'minority_number' => __('minority_number'),
            'left_behind_children_number'  => __('left_behind_children_number'),
            'disability_number'  => __('disability_number'),
            'file_card_account_number'  => __('file_card_account_number'),
            'five_guarantee_account_number'  => __('five_guarantee_account_number'),
            'low_income_household_number'  => __('low_income_household_number'),
            'created_at'  => __('created_at'),
        ];
    }

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

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

                // 设置表头样式
                $event->sheet->getDelegate()->getStyle('A1:AI1')->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 =  app(SchoolClass::class)->with(['province','city','county','township','village','group'])
            ->when($province_id = request('province_id', 0), function ($query) use ($province_id) {
                $query->where('province_id', $province_id);
            })
            ->when($para = request('city_id', 0), function ($query) use ($para) {
                $query->where('city_id', $para);
            })
            ->when($para = request('county_id', 0), function ($query) use ($para) {
                $query->where('county_id', $para);
            })
            ->when($para = request('township_id', 0), function ($query) use ($para) {
                $query->where('township_id', $para);
            })
            ->when($para = request('village_id', 0), function ($query) use ($para) {
                $query->where('village_id', $para);
            })
            ->when($para = request('group_id', 0), function ($query) use ($para) {
                $query->where('group_id', $para);
            })->when($para = request('belonged_org', 0), function ($query) use ($para) {
                $query->where('belonged_org', $para);
            })
            ->when($para = request('operation_org', 0), function ($query) use ($para) {
                $query->where('operation_org', $para);
            })
            ->when($para = request('class_sponsor', 0), function ($query) use ($para) {
                $query->where('class_sponsor', $para);
            })
            ->when($para = request('class_started_at', 0), function ($query) use ($para) {
                $query->whereDate('class_started_at', '>=', Arr::get($para, 'start'))
                    ->whereDate('class_started_at', '<=', Arr::get($para, 'end'));
            })
            ->when($para = request('class_closed_at', 0), function ($query) use ($para) {
                $query->whereDate('class_closed_at', '>=', Arr::get($para, 'start'))
                    ->whereDate('class_closed_at', '<=', Arr::get($para, 'end'));
            })
            ->when($para = request('name', 0), function ($query) use ($para) {
                $query->where('name', 'LIKE', '%' . $para . '%');
            })
            ->latest()->get();

        $data = $list->map(function ($item, $index) {
            return [
                $index+1,
                optional($item->province)->name,
                optional($item->city)->name,
                optional($item->county)->name,
                optional($item->township)->name,
                optional($item->village)->name,
                optional($item->group)->name,
                $item->name,
                format_date($item->class_started_at, 'Y-m-d'),
                format_date($item->class_closed_at, 'Y-m-d'),
                SystemConfig::getSingleSelectShowValue('belonged_org', $item->belonged_org),
                SystemConfig::getSingleSelectShowValue('operation_org', $item->operation_org),
                SystemConfig::getSingleSelectShowValue('class_sponsor', $item->class_sponsor),
                SystemConfig::getSingleSelectShowValue('class_mode', $item->class_mode),
                SystemConfig::getSingleSelectShowValue('class_type', $item->class_type),
                SystemConfig::getSingleSelectShowValue('class_location', $item->class_location),
                SystemConfig::getSingleSelectShowValue('class_policy', $item->class_policy),
                $item->class_service_hours,
                SystemConfig::getSingleSelectShowValue('whether_nap', $item->whether_nap, SystemConfig::getRadioOption()),
                SystemConfig::getSingleSelect2SingleSelectShowValue('whether_lunch', $item->whether_lunch, $item->whether_lunch_supplement),
                SystemConfig::getSingleSelect2MultipleSelectShowValue('outdoor_play_facilities', $item->outdoor_play_facilities, $item->outdoor_play_facilities_supplement, $item->outdoor_play_facilities_supplement_other),
                SystemConfig::getSingleSelect2MultipleSelectShowValue('indoor_play_facilities', $item->indoor_play_facilities, $item->indoor_play_facilities_supplement, $item->indoor_play_facilities_other),
                SystemConfig::getShowValueInput($item->family_committee, $item->family_committee_supplement),
                $item->other,
                $item->student_number,
                $item->boy_number,
                $item->girl_number,
                $item->han_nationality_number,
                $item->minority_number,
                $item->left_behind_children_number,
                $item->disability_number,
                $item->file_card_account_number,
                $item->five_guarantee_account_number,
                $item->low_income_household_number,
                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');
    }
}