Javascript href用于下载excel文件
我的服务器动态生成excel文件。我正在使用AJAX下载动态excel文件。在成功回调中,我收到excel文件数据Javascript href用于下载excel文件,javascript,ajax,excel,download,Javascript,Ajax,Excel,Download,我的服务器动态生成excel文件。我正在使用AJAX下载动态excel文件。在成功回调中,我收到excel文件数据 $.ajax({ url: exporting.action, headers: { "Authorization": "Basic " + btoa("key : " + key) }, type: "post", success: function(res){
$.ajax({
url: exporting.action,
headers: { "Authorization": "Basic " + btoa("key : " + key) },
type: "post",
success: function(res){
//res is the excel file that needs to be downloaded
//I know we can download image using anchor tag but not sure about excel file
},
data: { 'Model': JSON.stringify(modelClone) }
});
请建议如何在锚定标签的href
属性中使用此数据进行下载
注:
1) 我需要AJAX进行头授权通过添加
数据类型:“binary”
和响应类型:“arraybuffer”
属性来改进您的请求
$.ajax({
url: exporting.action,
headers: { "Authorization": "Basic " + btoa("key : " + key) },
type: "post",
responseType: "arraybuffer",
dataType: "binary",
success: function(res){
//res is the excel file that needs to be downloaded
//I know we can download image using anchor tag but not sure about excel file
},
data: { 'Model': JSON.stringify(modelClone) }
});
然后,您将收到数组缓冲区,可以通过Blob和对象URL轻松下载
var blob = new Blob([arraybuffer], {type: "application/vnd.ms-excel"});
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
就你而言:
$.ajax({
url: exporting.action,
headers: { "Authorization": "Basic " + btoa("key : " + key) },
type: "post",
success: function(res){
var blob = new Blob([res], {type: "application/vnd.ms-excel"});
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
},
data: { 'Model': JSON.stringify(modelClone) }
});
谢谢,我将尝试一下。问题是从服务器返回excel文件作为数组缓冲区。我无法控制来自服务器的数据。第三方库将其直接返回到客户端浏览器。我只将数据传递给第三方库是否可以将数据转换为客户端的数组缓冲区?您必须传递给库的内容以及库的输出内容是什么?我传递的是第三方图表实例。他们的库将创建一个带有图表的excel文件。输出是生成的excel文件的原始数据。