jquery - 通过 POST 下载 XLS 文件到 Spring MVC

标签 jquery spring-mvc xls

拜托,我对一个问题感到恼火。我需要下载一个在 Java 上动态创建的 xls。

这是我的客户端代码:

exportToExcel: function(filters, exportData) {
        $.ajax
        ({
            type: "POST",
            url: 'status/exportToExcel',
            async: true,
            data: {columns: exportData, filters: JSON.stringify(filters)},
            success: function (data) {
            var blob = new Blob([data], { "type" : "application/vnd.ms-excel" });
                var objectUrl = URL.createObjectURL(blob);
                window.open(URL.createObjectURL(objectUrl));
        },
        error: function (a,b,c){
        alert(c);
        }
    });
}

这是我的服务端代码:

@ResponseBody
@RequestMapping(value = "exportToExcel")
public void exportToExcel(
        @RequestParam(value = "columns", required = true) List<String> columns,
        @RequestParam(value = "filters", required = false) String filters, HttpServletRequest request){

    request.getHeaders().setContentType(getMediaType(excelFile));
    request.getHeaders().set("Content-Disposition", String.format("attachment; filename=%s.%s", excelFile.getName(), excelFile.getFormat()));

    try {
        FileCopyUtils.copy(new DataInputStream(new FileInputStream(excelFile.getFile())), httpOutputMessage.getBody());
    } catch (IOException e) {
        logger.error("Exception in file download", e);
    }catch(Exception e){
        logger.error("Exception in file download", e);
    }
}

我不知道如何显示下载对话框,如果是 GET 一个简单的 window.location 可以解决问题,但我的参数可能太大以至于 GET 无法解析。

最佳答案

@RequestMapping(value = "/exportToExcel", method = RequestMethod.POST)
@ResponseBody
public void exportToExcel(-, -, -, -, HttpServletRequest request,HttpServletResponse response )
{
    try{
    InputStream inputStream = service.calltoGetInputStream(); //logic to get inputstream
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"", "excelfilename.xlsx");
    response.setHeader(headerKey, headerValue);

    try {
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }
    }catch(Exception e){
        System.out.println("Exception in file download :"+e);
    }
}

关于jquery - 通过 POST 下载 XLS 文件到 Spring MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23479563/

相关文章:

iphone - 在 iOS 上创建 Excel XLS 文件

java - java中如何使文本适合xls列大小

java - Spring Request映射期

java - "Not supported for DML operations"使用简单的 UPDATE 查询

spring-mvc - hasPermission没有检查字段id怎么办?

javascript - jquery日期转换chrome可以工作,但IE和firefox不行

excel - Powershell - 将 .XLS 文件转换为 .XLSX

javascript - 在 Firefox 中禁用鼠标中键单击和拖动功能

jQuery 移动 : Changing button text when the button is clicked

javascript - 用它的宽度替换 div 高度(jquery)