dptt66700 2015-08-04 11:44
浏览 47
已采纳

Laravel Excel使用Controller下载

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');
}
  • 写回答

2条回答 默认 最新

  • drrkgbm6851 2017-04-08 09:54
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改