POI导出Excel不弹出保存提示_通过ajax异步请求(post)到后台通过POI导出Excel

实现导出excel的思路是:前端通过ajax的post请求,到后台处理数据,然后把流文件响应到客户端,供客户端下载

文件下载方法如下:

 public static boolean downloadLocal(HttpServletRequest request,String filePath, String fileName, HttpServletResponse response) throws Exception {
            // 读到流中
            InputStream inStream = new FileInputStream(filePath);// 文件的存放路径
            // 设置输出的格式
            response.reset();//清除首部的空白行
            // 文件编码 处理文件名中的 '+'、' ' 特殊字符
            String encoderName = null;
            String userAgent = request.getHeader("USER-AGENT");
            if(userAgent != null && userAgent.toLowerCase().indexOf("firefox") > 0){
                encoderName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
            }
            else {
                encoderName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20").replace("%2B", "+");
            }
            response.setHeader("Content-Disposition", "attachment;filename=\"" + encoderName + "\"");
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Accept-Ranges", "bytes");
        OutputStream ot = response.getOutputStream();
            // 循环取出流中的数据
            byte[] b = new byte[1024];
            int len;
            try {
                while ((len = inStream.read(b)) > 0)
                {
                    ot.write(b, 0, len);
                }
            } catch (Exception e) {
               
               
                return false;
            }finally{
                if(ot!=null){
                    ot.close();
                }
                if(inStream!=null){
                    inStream.close();
                }
                
            }
            return true;
        }

但是一直没有弹出保存提示,查资料后知道:ajax异步请求,dataType格式只支持有xml,html,script,json,jsonp,text,不支持二进制流文件类型

解决方法:
前端改成使用form表单提交方式即可

修改前端代码如下:

<body>
...
    <a class="mini-button mini-button-danger" onclick="exportCareerUnit()"  >导出</a>

...
...
    <form id="careerForm" action="${path}/mvc/career/exportCareerUnitMsg" style="display: none" method="post" >
            <input id="careerSubForm" name="careerSubForm" />
    </form>
</body>

<script>
    function exportCareerUnit(){

            var o = {
                sys:sysParam
          };
            $("#careerSubForm").val("");
            var json = JSON.stringify(o);
            $("#careerSubForm").val(json);
            $("#careerForm").submit(); //表单提交

    }
</script>

解决了问题!

后面看到另一篇文章:https://www.cnblogs.com/dingjiaoyang/p/5831049.html

“如果要将查询结果导出到Excel,只需将页面的Context-Type修改一下就可以了:header( "Content-Type: application/vnd.ms-excel">
如果希望能够提供那个打开/保存的对话框,设置Content-Disposition参数”

等忙过这阵,去试试~

猜你喜欢

转载自www.cnblogs.com/sunchunmei/p/12084972.html