spring-mvc下载动作

sal*_*sal 2 java excel spring-mvc download

是否有一些技巧可以让SpringMVC自定义视图在broswer中导致文件下载?我已经实现了该render方法,org.springframework.web.servlet.View但代码导致我的数据作为一个数据块写入页面,而不是开始下载操作.

try {

    Document oDoc = (Document) model.get("oDoc");
    out = new PrintWriter(response.getOutputStream());

    response.setContentType("application/vnd.ms-excel");
    response.setHeader("content-disposition", "attachment; filename=file.xls");

    GenerateXLSFile gof = new GenerateXLSFile();

    gof.outputTSVFromDom(out, oDoc);

} catch block here {

  //writes to log here

} finally {

    if (out != null) {
        out.flush();
        out.close();
    }

}
Run Code Online (Sandbox Code Playgroud)

我知道正在从服务器日志中调用render方法.我知道GenerateXLSFile是从服务器日志创建的.我知道outputTSVFromDom可以从我的JUnit测试中获取文档并对其进行转换.它还会写入服务器日志并完成.数据最终在浏览器中.根据firebug,HTTP标头看起来很正常.catch块中没有错误在服务器日志中.

我在这里错过了什么?

Dav*_*itz 5

首先,您使用的是哪种API?Excel文档是二进制文件,因此您应该使用OutputStream,而不是Writer.

其次,Spring内置了对Excel文档的支持: