Laravel Excel Download using Controller

吃可爱长大的小学妹 提交于 2019-12-10 18:04:27

问题


So I created a PHP Controller to handle exporting data which is posted by JS. The problem is I can see it creates something in the console but the file download never starts. I tried using ->store (laravel excel) and keeping it in an export folder but again when I try to use

return \Response::download($result);

it still won't start the download. The problem I'm having is just getting the download to start.

Angular Controller

$scope.exportMatrix = function () {
    var postData = {list: $scope.list, matrix: $scope.matrix};
    $http({
        method: 'POST',
        url: '/export',
        dataType: 'obj',
        data: postData,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function (data) {
        console.log(data);
    }).error(function (data) {
        console.log("failed");
    });
}

Route

Route::post('/export', 'ExportController@export');

PHP Controller

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App;
use Excel;
use Response;
class ExportController extends Controller {

public function export()
{

    $excel = App::make('excel');

    Excel::create('Test', function($excel) {
        $excel->setTitle('new awesome title');

        $excel->sheet('Sheet', function($sheet) {
            $sheet->fromArray(array(
                array('data1', 'data2'),
                array('data3', 'data4')
            ));
        });


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

回答1:


In the end I used FileSaver.js to download the blob it sent back so just load up FileSaver and use it saveAs(blob).

$http({
   method: 'POST',
   url: '/api/v1/download',
   dataType: 'json',
   data: {
       data:data
   },
   responseType: 'arraybuffer',
   headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data) {
   var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});

   saveAs(blob, title + ".xlsx");
}).error(function (data) {
   console.log("failed");
});

I made sure to use

responseType: arraybuffer

and saveAs type:

"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

Because reasons.




回答2:


Route::get('/export', 'ExportController@export');



来源:https://stackoverflow.com/questions/31808416/laravel-excel-download-using-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!