返回在servlet中创建的excel文件作为响应 [英] Return excel file created in servlet as response

查看:110
本文介绍了返回在servlet中创建的excel文件作为响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Apache POI 创建了excel文件并试图返回它作为对ajax调用的响应。我希望浏览器提示保存创建的文件窗口。
问题是我在servlet的响应中得到了gibbrish并且没有提示或任何提示

I've created excel file using Apache POI and tried to return it as response to ajax call. I want the browser to prompt "save the created file" window. The problem is that I get gibbrish in the servlet's response and no prompts or whatsoever

我在StackOverflow上发现了类似的问题,但解决方法是他们的问题对我不起作用(或者我错过了什么)。

I've found similar problems here, on StackOverflow, but the solutions to their issues doesn't work for me (or I miss something).

这里问题通过使用html标签解决了,但我不能(据我所知)在SAPUI5中使用它们。

Here the problem was solved by using html tags, but I can't (as far as I know) use them in SAPUI5.

此处是一个非常类似的案例,我用于此事,但它仍然不起作用。

And here is a very similar case, which I used for my matter, but it still doesn't work.

这是客户端代码:

jQuery.ajax({
            url : "Export",
            type : "post",
            mimeType: 'application/vnd.ms-excel',
            success : function(){
                console.log("data was exported successfully");
            },
            error: function(){

                console.log("error while exporting data");
            },
            complete: function(){
                console.log("exporting data has been completed");
            }
        });

这是servlet的代码:

And here is the servlet's code:

    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setHeader("Content-Disposition", "attachment; filename=ReportsData.xls");
    ServletOutputStream out = response.getOutputStream();
    workbook.write(out); 
    out.flush();
    out.close();

该文件是从中的数据库'select'wuery结果集创建的while(result.next())循环。

谢谢!

推荐答案

而不是使用ajax尝试制作一个在javascript中这样调用。

Instead of using ajax try making a call like this in javascript.

window.open(("urltoyourservlet"), "_blank");

这将打开一个直接链接到servlet的新窗口。然后浏览器应该自动处理基于mime / type下载excel文件的句柄。

This will open a new window linking directly to your servlet. Then the browser should automatically handle handle downloading the excel file based on the mime/type.

这篇关于返回在servlet中创建的excel文件作为响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆