Return excel file created in servlet as response

自古美人都是妖i 提交于 2020-01-23 09:20:40

问题


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

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

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.

Here is the client side code:

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");
            }
        });

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

The file is created from a database 'select' wuery result set in a while(result.next()) loop.

Thank you!


回答1:


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

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

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.



来源:https://stackoverflow.com/questions/26342891/return-excel-file-created-in-servlet-as-response

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!