I use the library as a means of generating Excel documents. Only I need to either save the file to the root/storage/app/public/export/file.xlsx directory, or immediately download the file in the browser. Everything is implemented in Laravel 9. Tell me how to write the code correctly?
My code, now:
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
...
$spreadsheet = new Spreadsheet();
$activeWorksheet = $spreadsheet->getActiveSheet();
$activeWorksheet->setCellValue('A1', 'Hello World !');
$writer = new Xlsx($spreadsheet);
$writer->save("file.xlsx");
The file is saved to a folder ‘public’.
Help me, please!
>Solution :
this will automatically download if you add ?download parameter to the URL, otherwise it it saves it at the storage_path
$spreadsheet = new Spreadsheet();
$activeWorksheet = $spreadsheet->getActiveSheet();
$activeWorksheet->setCellValue('A1', 'Hello World !');
$writer = new Xlsx($spreadsheet);
if (request()->has('download')) {
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="file.xlsx"');
header('Cache-Control: no-cache');
$writer->save('php://output');
} else {
$writer->save(storage_path('app/public/export/file.xlsx'));
}
return redirect()->back();