我正在使用以下包: Laravel版本5.1的版本2中的https://github.com/Maatwebsite/Laravel-Excel
我已经用下面的代码得到了控制器方法:
....
return Excel::create('List', function($excel) use ($list)
{
$excel->sheet('List', function($sheet) use ($list)
{
$sheet->fromModel($list);
});
})
->download('csv'); 像这样的简单测试:
$this->call('GET', 'route/to/csv', [
'param' => 'value',
]);
$this->dump();上面的测试从包的this line输出[ERROR]: Headers already sent。
控制器方法运行良好,但无法对其进行测试。
我试着用--stderr参数运行phpunit。在这种情况下,不会抛出错误,但它只是将CSV文件的输出转储到控制台并退出。我还尝试使用@runInSeparateProcess注释运行测试,得到如下错误:
PHPUnit_Framework_Exception: PHP Notice: Constant LARAVEL_START already defined in bootstrap/autoload.php on line 3
....
PHP Fatal error: Uncaught exception 'ReflectionException' with message 'Class env does not exist' in vendor/laravel/framework/src/Illuminate/Container/Container.php:736这可能是Laravel-Excel包中的错误,还是我测试错了?
发布于 2017-04-20 04:49:46
这是因为download方法在laravel excel中的工作方式是通过设置头。您希望避免这种情况,而是通过返回laravel响应来自己完成所有工作。
试着这样做:
$file = Excel::create('List', function($excel) use ($list) {
$excel->sheet('List', function($sheet) use ($list)
{
$sheet->fromModel($list);
});
})->string('xls');
return new Response($file, 200, [
'Content-Type' => 'application/vnd.ms-excel; charset=UTF-8',
'Content-Disposition' => 'attachment; filename="' . $file->filename . '.' . $file->ext . '"',
'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', // Date in the past
'Last-Modified' => Carbon::now()->format('D, d M Y H:i:s'),
'Cache-Control' => 'cache, must-revalidate',
'Pragma' => 'public',
]);关键区别在于使用string()方法,该方法将返回excel文件的二进制数据,并允许您将其作为响应的数据进行传递。
https://stackoverflow.com/questions/31875986
复制相似问题