特殊行索引(1 起)=> 类型(title/header/summary) */ private array $specialRows = []; /** 列头所在行索引 */ private int $headerRow = 1; public function __construct( private readonly PurchaseOrderModel $purchase, private readonly SupplierModel $supplier, private readonly string $sheetTitle, ) { } /** * 导出行:标题/空行/列头/明细/合计 */ public function collection(): Collection { if ($this->rows !== null) { return $this->rows; } $items = app(PurchaseItemService::class)->supplierRows($this->purchase->id, $this->supplier->id); $rows = []; $rowIndex = 0; // 标题行 $rows[] = [$this->supplier->name . ' · 采购单 ' . $this->purchase->purchase_no]; $this->specialRows[++$rowIndex] = 'title'; // 空行 $rows[] = ['']; $rowIndex++; // 列头 $rows[] = ['序号', '品名', '包规', '单位', '成本价', '数量', '重量(斤)', '金额']; $this->specialRows[++$rowIndex] = 'header'; $this->headerRow = $rowIndex; // 明细行 $totalQuantity = 0; $totalWeight = '0'; $totalAmount = '0'; foreach (array_values($items) as $sort => $item) { $rows[] = [ $sort + 1, $item['product_name'], $item['product_spec'], $item['unit'], (float) $item['cost_price'], (int) $item['quantity'], (float) $item['weight'], (float) $item['amount'], ]; $rowIndex++; $totalQuantity += (int) $item['quantity']; $totalWeight = bcadd($totalWeight, (string) $item['weight'], 3); $totalAmount = bcadd($totalAmount, (string) $item['amount'], 2); } // 合计行 $rows[] = ['', '合计', '', '', '', $totalQuantity, (float) $totalWeight, (float) $totalAmount]; $this->specialRows[++$rowIndex] = 'summary'; return $this->rows = collect($rows); } public function title(): string { return $this->sheetTitle; } /** * 标题/列头/合计加粗,冻结列头 */ public function styles(Worksheet $sheet): array { $this->collection(); $sheet->freezePane('A' . ($this->headerRow + 1)); $widths = [6, 24, 14, 8, 10, 10, 12, 12]; foreach ($widths as $index => $width) { $sheet->getColumnDimension(Coordinate::stringFromColumnIndex($index + 1))->setWidth($width); } $styles = []; foreach ($this->specialRows as $row => $type) { $style = match ($type) { 'title' => ['font' => ['bold' => true, 'size' => 14]], 'header', 'summary' => ['font' => ['bold' => true]], default => [], }; if ($style !== []) { $styles[$row] = $style; } } return $styles; } }