Php 如何在laravel中使用ajax有条件地导出CSV?
我正在尝试使用Laravel Excel包导出CSV。 我需要在使用ajax请求时传递一些变量,这一切都正常,但响应没有下载CSV 我在一些没有ajax的地方使用了这个包,只是一个简单的导出,而且一切正常,所以我知道这方面都很好 下面是我用来发送数据的ajax:Php 如何在laravel中使用ajax有条件地导出CSV?,php,excel,ajax,laravel,response,Php,Excel,Ajax,Laravel,Response,我正在尝试使用Laravel Excel包导出CSV。 我需要在使用ajax请求时传递一些变量,这一切都正常,但响应没有下载CSV 我在一些没有ajax的地方使用了这个包,只是一个简单的导出,而且一切正常,所以我知道这方面都很好 下面是我用来发送数据的ajax: $(document).ready(function() { $( "#export" ).on( "click", function() { let clubInfo = $("#clubInfo se
$(document).ready(function() {
$( "#export" ).on( "click", function() {
let clubInfo = $("#clubInfo select").val();
let funderInfo = $("#funderInfo select").val();
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
type: 'post',
url: '{{route('export')}}',
data: {club : clubInfo, funder: funderInfo},
}).done(function(response) {
console.log(response);
}).fail(function() {
console.log("Failed");
});
});
});
以下是处理导出的控制器:
public function adminExport(Request $request)
{
$club = $request->input('club');
$funder = $request->input('funder');
return Excel::download(new UsersExport($club, $funder), 'users.xlsx');
}
我没有收到任何PHP错误或警告,这一切都很好,我只是在网络选项卡中得到一个响应,它看起来像是csv,只是没有下载。
响应的标题为:
Accept-Ranges: none
Cache-Control: public
Connection: keep-alive
Content-Disposition: attachment; filename=users.xlsx
Content-Length: 6812
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
除非通过AJAX获取文件是一项非常困难的要求,否则我建议使用
window.open('your_url/your_route?club=XXXXX&funder=XXXXX','u blank')
下载文件并避免任何麻烦。我认为您需要告知导出类型。注意以下几点:
return (new InvoicesExport)->download('invoices.csv', \Maatwebsite\Excel\Excel::CSV);
但在您的控制器中,我看不到导出类型:
return Excel::download(new UsersExport($club, $funder), 'users.xlsx');
如果您使用的是2.1版,则需要执行以下操作:
Excel::create('Filename', function($excel) {
//
})->export('csv');
或者。。。您认为如何先保存导出,然后再像这样导出
$file_name = 'my_export';
// Find users first
$users = User::where([['club', $club], ['funder', $funder]])->get();
// then generate the file
Excel::create($file_name, function ($excel) use ($users) {
$excel->sheet('Users', function($sheet) use($users) {
$sheet->fromArray($users);
});
})->store('csv', storage_path('excel/export'));
// Finally, download the file
$full_path = storage_path('excel/export') . '/' . $file_name . '.csv';
return Storage::disk('public')->download($full_path, $file_name . 'csv',
['Content-Description' => 'File Transfer','Content-Type' => 'application/octet-
stream','Content-Disposition' => 'attachment; filename=' . $file_name .
'.csv']);
或者你可以这样做:
$headers = array(
'Content-Type' => 'text/csv',
);
return Response::download($file_name . 'csv', $full_path, $headers);
这些是作为ajax响应的标题。你必须自己触发下载。如果excel工作表的二进制数据出现在响应中,那么您可以在javascript中创建一个对象URL,将此URL设置为锚定标记,然后单击它进行下载。在这种情况下,不要使用ajax简单提交表单和普通php,它将下载。