Laravel Excel 使用 Ajax 请求,没办法下载如何处理?(有方案)[vue][axios][Excel]
在使用 element-ui 开发的过程中,有需求时需要导出excel报表的。
选择的(laravel excel)[https://github.com/Maatwebsite/Laravel-Exc...] 处理导出,但是发现通过ajax的请求,都不会成功的下载。
查找了资料,发现如下几个方案:
- axios 增加 responseType:arraybuffer。 参考
尝试未生效 - 保存在服务器,然后前端请求下载
未尝试,应该可行。I was able to solve the problem. I'm using 'store' method to save the file on the server, and then I send the response (the path to the file):
export.done(function (data) {
window.location.href = data;
});And the file can be donwloaded.
- 直接在新窗口打开,可以成功下载 尝试可行,需重新拼接url
window.location.href= queryString;
- laravel 返回json数据,然后模拟自动点击a标签下载 参考
$myFile= Excel::create("filename", function($excel) use($data) { $excel->setTitle('title'); $excel->sheet('sheet 1', function($sheet) use($data) { $sheet->fromArray($data, null, 'A1', true, true); }); }); $myFile = $myFile->string('xlsx'); //change xlsx for the format you want, default is xls $response = array( 'name' => "filename", //no extention needed 'file' => "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,".base64_encode($myFile) //mime type of used format ); return response()->json($response);
ajax 内容:
$.ajax({ cache: false, url: url, //GET route data: params, //your parameters data here success: function (response, textStatus, request) { var a = document.createElement("a"); a.href = response.file; a.download = response.name; document.body.appendChild(a); a.click(); a.remove(); }, error: function (ajaxContext) { toastr.error('Export error: '+ajaxContext.responseText); } });
问题如下:
有遇到过类似问题的吗,一般使用什么方法解决?
现在有导入excel,如果有不符合的数据,需要导出,要怎么处理,选择方案2?
有其他方法的欢迎补充~
我的方案是不用 ajax, 直接拼一个 GET 请求的接口, 也就是一个 url, 然后
Excel::create()->download('xlsx);
@小恪守 这个应该是比较便捷的方案了
可以先给一个url, 然后通过这个url下载;
@猪爷爷 果然还是不能直接请求下载,网上找了半天
@猪爷爷 不能是个url,,url任何人都能下载,,最好是个下载的接口,,这样能控制权限...
ajax
成功后,在success
中使用window.location.href = ''
试试可以看下我写的ajax下载文件的,希望对你有帮助 博客:Ajax 下载文件
@limin 接口中怎么返回excel文件呢
应该是用 responseType:blob https://github.com/axios/axios/issues/448#...
这真是个大坑