刚开始使用ajax作Excel导出,发现ajax作不了浏览器导出只能下载到本地,因而用form提交能够提供浏览器下载Excel。html
1>用ajax作本地下载:jquery
FileOutputStream fout = new FileOutputStream("C:/student.xls");
.write(fout);
fout.close();ajax
2>用form作浏览器下载:json
jsp:HTML:浏览器
<form id="myform" name="myform" method="post" action="" style="float:right;">
<input type="hidden" name="year" >
<input type="button" id="jqueryBtn" onclick="exportData()" value="导出数据" /></form>app
js:异步
document.getElementById("myform").setAttribute("action", url);//url提交的路径
document.getElementById("myform").year.value = str;//提交的参数值
document.getElementById("myform").submit();jsp
Java:post
String name = new String((fileName.getBytes("GBK")), "ISO8859_1");
OutputStream os = response.getOutputStream();
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename=" + name);
wb.write(os);
os.flush();
os.close();url
ajax不能导出的缘由:ajax请求只是个“字符型”的请求,即请求的内容是以文本类型存放的。文件的下载是以二进制形式进行的,ajax无法解析后台返回的文件流,因此没法处理二进制流response输出来下载文件;经过ajax异步传输的数据格式有三种,分别是html、xml以及json格式,不能传递流的格式。