CSV导出在laravel 5控制器 [英] CSV export in laravel 5 controller
问题描述
所以我向我的 reviewsController @ export
发出了一个ajax请求。
So I have made a little ajax request to my reviewsController@export
.
c $ c> console.log()在我的成功方法中的数据,ajax响应显示正确的数据。但是我的CSV尚未下载。所以我有所有正确的信息,并基本上创建了csv。
Now when I console.log()
the data in my success method, the ajax response shows the correct data. However my CSV has not downloaded. So I have all the right info and have created the csv essentially.
我想这可能与设置标题可能?
I think this has possibly to do with setting the headers maybe?
public function export()
{
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$reviews = Reviews::getReviewExport($this->hw->healthwatchID)->get();
$columns = array('ReviewID', 'Provider', 'Title', 'Review', 'Location', 'Created', 'Anonymous', 'Escalate', 'Rating', 'Name');
$file = fopen('php://output', 'w');
fputcsv($file, $columns);
foreach($reviews as $review) {
fputcsv($file, array($review->reviewID,$review->provider,$review->title,$review->review,$review->location,$review->review_created,$review->anon,$review->escalate,$review->rating,$review->name));
}
exit();
}
有什么我在这里做错了,对于这个?
Is there anything I am doing wrong here, or does Laravel have something to cater for this?
推荐答案
尝试这个版本 - 这应该允许你使用 :: stream()
。
Try this version out - this should allow you to get a nice output using Response::stream()
.
public function export()
{
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=file.csv",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);
$reviews = Reviews::getReviewExport($this->hw->healthwatchID)->get();
$columns = array('ReviewID', 'Provider', 'Title', 'Review', 'Location', 'Created', 'Anonymous', 'Escalate', 'Rating', 'Name');
$callback = function() use ($reviews, $columns)
{
$file = fopen('php://output', 'w');
fputcsv($file, $columns);
foreach($reviews as $review) {
fputcsv($file, array($review->reviewID,$review->provider,$review->title,$review->review,$review->location,$review->review_created,$review->anon,$review->escalate,$review->rating,$review->name));
}
fclose();
};
return Response::stream($callback, 200, $headers);
}
(根据这个SO回答:使用Laravel将表格下载为CSV )
(Adapted from this SO answer: Use Laravel to Download table as CSV)
尝试使用 target =_ blank
的常规链接,而不是使用JavaScript / AJAX。由于这是一个在新标签页中打开的文件下载,用户体验不应太笨重。
Try using a regular link with target="_blank"
rather than using JavaScript/AJAX. Because it's a file download opening in a new tab, the user experience shouldn't be too clunky.
这篇关于CSV导出在laravel 5控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!