skip to Main Content

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 PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;
...
    $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!

3

Answers


  1. if your file is saved in the public folder you can download it easily.

    return response()->download(public_path('file_path'));
    

    more the similar question is already here please have a read,

    Login or Signup to reply.
  2. if you want to add into storage, use storage feature,

    $originalName = $yourfilename;
    $path = "/public/export/".$originalName;
    Storage::disk('local')->put($path, file_get_contents($yourfile));
    

    the storage::disk(‘local’) setting is in config/filesystem.php, you can custom the path you want, you can see that default path is going to storage/app

    or if you want download it directly, you can use datatables of yajra at your view, you can export it as dpf, excel, xlsx.

    $(document).ready(function() {
        $('#example').DataTable( {
            dom: 'Bfrtip',
            buttons: [
                'copy', 'csv', 'excel', 'pdf', 'print'
            ]
        } );
    } );
    

    here is the references => datatable export

    due to lack information from your question, i cant fit your code into my answer, but i hope you understand what i explained

    Login or Signup to reply.
  3. 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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search