使用Laravel将表格下载为CSV

使用Laravel将表格下载为CSV

问题描述:

我试图使用 Laravel 作为 csv 文件导出数据库表。我希望用户能够选择导出为CSV 按钮并将该表下载为 csv 文件。目前我已获得此代码,但它不工作:

I am trying to export a database table using Laravel as a csv file. I would like the user to be able to select the Export as CSV button and download the table as a csv file. Currently I've gotten this code but It is not working:

我的按钮:

<a href="/all-tweets-csv" class="btn btn-primary">Export as CSV</a>

我的路线:

Route::get('/all-tweets-csv', function(){

    $table = Tweet::all();
    $filename = "tweets.csv";
    $handle = fopen($filename, 'w+');
    fputcsv($handle, array('tweet text', 'screen name', 'name', 'created at'));

    foreach($table as $row) {
        fputcsv($handle, array($row['tweet_text'], $row['screen_name'], $row['name'], $row['created_at']));
    }

    fclose($handle);

    $headers = array(
        'Content-Type' => 'text/csv',
    );

    return Response::download($handle, 'tweets.csv', $headers);
});

它返回我这个错误:

 The file "Resource id #154" does not exist

我收集,这是因为它是试图下载一个不存在的文件。有一个替代方法,我可以去修改我的代码,以便下载为 csv

And I've gathered that it is because it is trying to download a file that does not exist. Is there an alternative way I can go about modifying my code in order to download as a csv.

几乎一切都很好,除了这一行:

Almost everything is fine except this line:

return Response::download($handle, 'tweets.csv', $headers);

您应该将此行更改为:

return Response::download($filename, 'tweets.csv', $headers);