write($rows, $path); return response()->download($path, basename($filename))->deleteFileAfterSend(true); } public function store(Collection $rows, string $filename, ?string $disk = null): string { $tmp = storage_path(self::EXPORT_DIRECTORY . uniqid('', true) . '-' . basename($filename)); $this->write($rows, $tmp); if ($disk && config("filesystems.disks.$disk")) { Storage::disk($disk)->put($filename, file_get_contents($tmp)); @unlink($tmp); return $filename; } return $tmp; } public function storeSheets(array $sheets, string $filename, ?string $disk = null): string { $book = new Spreadsheet; $book->removeSheetByIndex(0); foreach ($sheets as $title => $rows) { $sheet = $book->createSheet(); $sheet->setTitle(substr((string) $title, 0, 31)); $array = collect($rows)->map(fn ($row) => (array) $row)->values(); if ($array->isNotEmpty()) { $sheet->fromArray($array->map(fn ($row) => array_values($row))->all(), null, 'A1'); } } $tmp = storage_path(self::EXPORT_DIRECTORY . uniqid('', true) . '-' . basename($filename)); if (! is_dir(dirname($tmp))) { mkdir(dirname($tmp), 0775, true); } (new Xlsx($book))->save($tmp); if ($disk && config("filesystems.disks.$disk")) { Storage::disk($disk)->put($filename, file_get_contents($tmp)); @unlink($tmp); return $filename; } return $tmp; } private function write(Collection $rows, string $path): void { if (! is_dir(dirname($path))) { mkdir(dirname($path), 0775, true); } $sheet = (new Spreadsheet)->getActiveSheet(); $array = $rows->map(fn ($row) => (array) $row)->values(); $headers = $array->first() ? array_keys($array->first()) : []; if ($headers) { $sheet->fromArray($headers, null, 'A1'); $sheet->fromArray($array->map(fn ($row) => array_values($row))->all(), null, 'A2'); } (new Xlsx($sheet->getParent()))->save($path); } }