Search code examples
phphttp-headerslaravel-5.1xlsx

Laravel-Excel xlsx download request not working


I'm using the Maatwebsite/Laravel-Excel(version 2.1) library in Laravel to download an xls file.

class ControllerApi extends Controller {

     private $excel;

     public function __construct(Excel $excel) {
         $this->excel = $excel;
     }

     public function getXlsFile(Request $request) {
           $this->excel->create("Report2016", function($excel) {

            // Set the title
            $excel->setTitle('My awesome report 2016');

            // Chain the setters
            $excel->setCreator('Me')->setCompany('Our Code World');

            $excel->setDescription('A demonstration to change the file properties');

            $data = [12,"Hey",123,4234,5632435,"Nope",345,345,345,345];

            $excel->sheet('Sheet 1', function ($sheet) use ($data) {
                $sheet->setOrientation('landscape');
                $sheet->fromArray($data, NULL, 'A3');
            });

        })->export("xlsx");
     }
}

enter image description here

enter image description here

Even though the response header seems to be okay, the browser don't download the file.

Anyone knows what I'm doing wrong?

Thanks in advance.


Solution

  • You can't just download something from a ajax request. Your frontend likely should be doing some extra steps like creating an link with the content of that call.

    EDIT

    I can't put some code specificaly for you, as I have no idea how the frontend is made. But you could use a lib as https://github.com/eligrey/FileSaver.js/.

    For example, as you are downloading some binary data for a spreadsheet:

    http('yourBackendUrl').then(function(response) {
    
        var blobData = new Blob([response.data], {type: "application/xlsx"})
        saveAs(blobData, filename+'.xlsx')
    
    }