Spring mvc用javascript下载xls

时间:2018-02-07 12:26:51

标签: javascript java excel spring spring-mvc

我有一个Web应用程序,我想下载一个xls文件。 spring-boot中的控制器将通过get请求返回SELECT COUNT,seller,purchaser FROM YourTable ORDER BY seller,purchaser DESC

HttpServletResponse

在客户端我想将文件导出到xls,这是代码:

@RequestMapping(method = RequestMethod.GET, value = "/export/{id}", produces = { "multipart/mixed", "multipart/form-data" })
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public void export(@PathVariable String id, HttpServletResponse response) {
    XSSFWorkbook wb = service.export(assessmentId);
    String filename="test.xlsx";
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition", "attachment; filename=test.xlsx");

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        wb.write(bos);
        byte[] barray = bos.toByteArray();
        InputStream is = new ByteArrayInputStream(barray);
        IOUtils.copy(is, response.getOutputStream());

    } catch (IOException e) {    
        e.printStackTrace();
    }
}

尝试打开xlsx文件时,我的文件已损坏。

1 个答案:

答案 0 :(得分:2)

你有没有理由不能send the file as a download from the controller?在HTML中使用类似

的内容
<a href="/export/124875"><i class="fa fa-download"></i></a>