form表单提交方式实现浏览器导出Excel

刚开始使用ajax做Excel导出,发现ajax做不了浏览器导出只能下载到本地,于是用form提交可以提供浏览器下载Excel。

1>用ajax做本地下载:

  FileOutputStream fout = new FileOutputStream("C:/student.xls");
  .write(fout);
   fout.close();

2>用form做浏览器下载:

  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>

    js:

    document.getElementById("myform").setAttribute("action", url);//url提交的路径
    document.getElementById("myform").year.value = str;//提交的参数值 
    document.getElementById("myform").submit();

  Java:

    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();

ajax不能导出的原因:ajax请求只是个“字符型”的请求,即请求的内容是以文本类型存放的。文件的下载是以二进制形式进行的,ajax没法解析后台返回的文件流,所以无法处理二进制流response输出来下载文件;通过ajax异步传输的数据格式有三种,分别是html、xml以及json格式,不能传递流的格式。

猜你喜欢

转载自www.cnblogs.com/yjwww/p/9470140.html
今日推荐