| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- <?php
- namespace App\Exports;
- use Illuminate\Support\Collection;
- use Maatwebsite\Excel\Concerns\FromCollection;
- use Maatwebsite\Excel\Concerns\WithTitle;
- use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
- use Maatwebsite\Excel\Concerns\WithStyles;
- use PhpOffice\PhpSpreadsheet\Cell\Cell;
- use PhpOffice\PhpSpreadsheet\Cell\DataType;
- use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder;
- use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
- use PhpOffice\PhpSpreadsheet\Style\Alignment;
- use PhpOffice\PhpSpreadsheet\Style\Border;
- class SingleSheetExport extends DefaultValueBinder implements FromCollection, WithTitle, WithCustomValueBinder, WithStyles
- {
- protected $data;
- protected $sheetName;
- public function __construct(array $data, string $sheetName)
- {
- $this->data = $data;
- $this->sheetName = $sheetName;
- }
- /**
- * 数据集合
- */
- public function collection()
- {
- return new Collection($this->data);
- }
- /**
- * Sheet 名称
- */
- public function title(): string
- {
- return $this->sheetName;
- }
- /**
- * 自定义单元格绑定(防止数字丢失前导零 / 科学计数法)
- */
- public function bindValue(Cell $cell, $value)
- {
- // 如果是纯数字,则以字符串形式写入
- if (is_numeric($value)) {
- $cell->setValueExplicit($value, DataType::TYPE_STRING);
- return true;
- }
- return parent::bindValue($cell, $value);
- }
- /**
- * 每页 Sheet 的样式
- */
- public function styles(Worksheet $sheet)
- {
- $highestRow = $sheet->getHighestRow();
- $highestColumn = $sheet->getHighestColumn();
- // 1. 表头加粗、居中
- $sheet->getStyle('A1:' . $highestColumn . '1')->applyFromArray([
- 'font' => [
- 'bold' => true,
- 'size' => 11,
- ],
- 'alignment' => [
- 'horizontal' => Alignment::HORIZONTAL_CENTER,
- 'vertical' => Alignment::VERTICAL_CENTER,
- ],
- 'borders' => [
- 'bottom' => ['borderStyle' => Border::BORDER_THIN],
- ],
- ]);
- // 2. 内容垂直居中
- $sheet->getStyle('A2:' . $highestColumn . $highestRow)
- ->getAlignment()
- ->setVertical(Alignment::VERTICAL_CENTER);
- // 3. 自动列宽
- foreach (range('A', $highestColumn) as $col) {
- $sheet->getColumnDimension($col)->setAutoSize(true);
- }
- return [];
- }
- }
|