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条)

报告相同问题?

悬赏问题

  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 YOLOv8obb获取边框坐标时报错AttributeError: 'NoneType' object has no attribute 'xywhr'
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?