导出CSV响应laravel 5.5并下载为csv文件

时间:2018-02-15 08:19:10

标签: laravel export-to-csv

我正在尝试使用ajax请求导出和下载csv文件中的一些数据。我能够在json响应中输出数据进行测试但无法在data.csv文件中下载

以下是我到目前为止编写的代码

   public function download(Request $request)
    {

        if(!empty($request->input('my_checkbox')))
        {
             $studentIdToExportArray = $request->input('my_checkbox');
            //$msg = is_array($studentIdToExportArray);//returns true
            $selectedStudents = [];   
            foreach($studentIdToExportArray as $student_id)
            {
                    $student = Students::find($student_id);
                    array_push($selectedStudents, $student);
            }
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=data.csv');
            $output=fopen("php://output","w");
            fputcsv($output,array("ID","firstname","surname","email","nationality","address_id","course_id"));

            foreach($selectedStudents as $s1)
            {
                $array = json_decode(json_encode($s1), true);
                fputcsv($output, $array);
            }
            fclose($output);    

            return response()->json([
                   'test'=> $selectedStudents 
            ]);           
        }


    }

控制台

中输出响应的屏幕截图

enter image description here

问题:文件data.csv无法下载

2 个答案:

答案 0 :(得分:1)

<强>尝试:

$file=fopen('../storage/app/test.csv','w');

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

$path = storage_path('test.csv');
return response()->download($path, 'test.csv', $headers);

答案 1 :(得分:0)

首先,您必须将文件保存到本地或云盘上的某个位置,然后执行文件响应或下载响应。这些是文档中显示的下载选项: https://laravel.com/docs/5.5/responses#file-responses

return response()->download($pathToFile);

return response()->download($pathToFile, $name, $headers);

return response()->download($pathToFile)->deleteFileAfterSend(true)

ps:你也可以看一下使用专用软件包,或者只使用软件包作为参考。 https://github.com/Maatwebsite/Laravel-Excel