在春天生成的电子表格具有错误的扩展名

时间:2015-04-27 01:16:19

标签: java spring servlets

我正在尝试从spring应用程序生成Excel电子表格。它是用.do扩展而不是.xls生成的。但是,如果我将下载的文件重命名为.xls,我可以在Excel中看到我的所有内容。我的控制器代码如下。

    @RequestMapping(value="getReportsList.do")
    public ModelAndView getReports(HttpServletRequest request,
            HttpServletResponse response,
            @ModelAttribute("ordCommand") OrdCommand ordCommand,
        BindingResult errors) throws Exception {

    ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
    List<Object[]> recordsArray = null;


    try {

        List<ReportVO> recordsArray = ordService.getDCTrackReports();


        if (null != recordsArray ) {
            //excel formatting code
        }

        response.setHeader("Cache-Control", "public");
        response.setHeader("Pragma", "public");
        response.setHeader("Expires", "0");
        response.setHeader("Content-Disposition", "my_report.xls");
        response.setContentType("application/vnd.ms-excel");
    //  ServletOutputStream out = response.getOutputStream()
        if (byteArrayStream != null) {
            response.getOutputStream().write(byteArrayStream.toByteArray());
        }
        response.getOutputStream().flush();
        byteArrayStream.flush();
        byteArrayStream.close();
    } catch (Exception e) {
        e.getMessage();
    }

    return null;

}

2 个答案:

答案 0 :(得分:1)

请尝试设置Content-Disposition标头:

 response.setHeader("Content-Disposition", "inline:filename=\"my_report.xls\"");

&#34; inline&#34;之间的差异和&#34;附件&#34;:Content-Disposition:What are the differences between "inline" and "attachment"?

内容处置标题https://tools.ietf.org/html/rfc6266

答案 1 :(得分:1)

在Content-Disposition中添加文件名并添加为附件,并将内容类型添加到带附件的响应

 response.setHeader("Content-Disposition","attachment; filename=my_report.xls");
 response.setHeader("Content-Type", "application/vnd.ms-excel");

这是肯定的。