使用jquery ajax和servlet导出到excel

时间:2014-12-14 04:50:38

标签: jquery ajax excel servlets

我在编写代码以将数据(来自服务器)导出到excel文件时遇到问题。我写了这么简单的代码。

ajax调用我的导出到excel servlet。

 $.ajax({
                url : "http://localhost:8800/project/abc/export", 
                type: "POST",
                data : data,          
                dataType: "text",
               /* contentType: "application/vnd.ms-excel",*/
                success : function(data, text_status, XMLHttpRequest) {
                    console.log("export done");         
                },
                error : function(XMLHttpRequest, text_status, error) {
                    console.log("error"+text_status+":::"+error);
                }
            });

以下是我的Servlet代码:

@Path("/abc")
public class Resource {


    @POST
    @Path("/export")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces("application/vnd.ms-excel")
    public Response exportResults(@Context HttpServletRequest req,@Context HttpServletResponse resp) {
        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("results");
        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("tttttt");        
        File f =new File("new-excel-file.xls");     
        FileOutputStream fos;
        ResponseBuilder response = null ;
        try {
            fos = new FileOutputStream(f);
             wb.write(fos);  
             response= Response.ok((Object) f);

                fos.close(); 
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }           

        response.header("Content-Disposition",
                "attachment; filename=new-excel-file.xls");
         response.header("Content-Type","application/octet-stream"); 
        return response.build();
    }

}

我希望在我的ajax调用完成后弹出一个要求保存文件。我可以看到在ajax调用之后打印数据但是没有弹出窗口。有人可以帮我这个。

我的ajax请求是POST请求,因此我无法使用window.location = url。

0 个答案:

没有答案