'序号', 'width' => 8, ], [ 'name' => '学号', 'width' => 15, 'field' => 'account' ], [ 'name' => '姓名', 'width' => 20, 'field' => 'name' ], [ 'name' => '性别', 'width' => 10, ], [ 'name' => '班级', 'width' => 20, ], [ 'name' => '手机号', 'width' => 20, 'field' => 'mobile' ], [ 'name' => '邮箱', 'width' => 20, 'field' => 'email' ], [ 'name' => '状态', 'width' => 10, ], ]; protected $rowNums = 0; protected $ids = []; protected $lastC = 'A'; protected $fields = []; public function __construct($ids, $field_ids = []) { $this->ids = $ids; $fields = []; if (!is_array($field_ids) || !count($field_ids)) { $fields = self::BaseFields; } else { foreach ($field_ids as $field_id) { $fields[] = self::BaseFields[$field_id]; } } $this->fields = $fields; } public function query() { $ids = $this->ids; $model = Student::query(); if (!count($ids)) return $model->where('id', 0); return $model ->with(['grade']) ->whereIn('id', $ids)->orderByDesc('id'); } public function map($row): array { $row = $row->toArray(); $this->rowNums++; $data = []; foreach ($this->fields as $k => $col) { $name = $col['name']; if ($name == '序号') $data[$k] = $this->rowNums; if (isset($col['field'])) { $data[$k] = $row[$col['field']]; continue; } if ($name == '性别') { $sex_name = ''; switch ((int)$row['sex']) { case 1: $sex_name = '男'; break; case 2: $sex_name = '女'; break; } $data[$k] = $sex_name; continue; } if ($name == '班级') { $data[$k] = getVal($row['grade']['name']); continue; } if ($name == '状态') { $data[$k] = ModelStatusEnum::getDescription($row['status']); continue; } } return $data; } public function headings(): array { $room_name = '学生数据'; $data[] = [$room_name]; $data[] = array_column($this->fields, 'name'); return $data; } public function headingRow(): int { return 2; } public function columnWidths(): array { $i = 65; $data = []; foreach ($this->fields as $k => $field) { $s = intval($k / 26); if (!$s) $key = chr($i + $k); if ($s > 0) { $y = intval($k % 26); $key = chr($s + $i - 1); $key .= chr($y + $i); } $data["{$key}"] = $field['width']; $this->lastC = $key; } return $data; } public function styles(Worksheet $sheet) { $last = $this->lastC; $cellRange = "A1:{$last}1"; $sheet->getStyle($cellRange)->getFont()->setSize(12); $sheet->getDefaultRowDimension()->setRowHeight(40);//设置行高 // 文字居中 $lastrow = $sheet->getHighestRow(); $sheet->getStyle("A1:{$last}" . $lastrow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);//垂直居中 $sheet->getStyle("A1:{$last}" . $lastrow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER); $sheet->getStyle("A1:{$last}" . $lastrow)->getAlignment()->setWrapText(true); $sheet->mergeCells("A1:{$last}1"); //合并 $sheet->getStyle("A1:{$last}1")->getFont()->setSize(16); } }