Ajax方式导出Excel,浏览器显示下载Excel表

 

之前实现导出Excel,都是用form表单提交,由于jquery封装的ajax请求导出Excel,浏览器不显示文件。html

可是此次的需求要带着header,form表单不能带header,百度了下,原生ajax是支持导出Excel的二进制数据格式的。jquery

 

 

 

一、JS方法里所有代码ajax

 

//原生ajax
var xhr = new XMLHttpRequest();
//post方式请求后台的路径
xhr.open('post', '/api/export', true);
//导出的Excel是二进制数据类型,因此设置为blob
xhr.responseType = 'blob';
//请求头(key,value),请求头能够设置多个key-value对
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
//返回成功,导出的Excel文件
xhr.onload = function () {
	if (this.status == 200) {
		var blob = this.response;
		var a = document.createElement('a');
		var url = window.URL.createObjectURL(blob);
		a.href = url;
		//设置文件名称
		a.download = 'Excel文件名字.xlsx';
		a.click();
	}
}
var feeDate = $('#feeDate').val();
//请求的参数,json格式,后台要用json格式接收
xhr.send(JSON.stringify({
   "feeDate" : feeDate
}));

  

 

 form表单导出Excel,请参照json

 http://www.javashuo.com/article/p-vacputmh-dp.htmlapi

相关文章
相关标签/搜索