弹出mvc下载的Xlsx文件已损坏,内容类型已更改

时间:2017-07-31 12:54:53

标签: java spring jsp spring-mvc apache-poi

调用服务并使用apache-poi生成xlsx并返回视图的控制器方法。

@RequestMapping(value = "/getSummary", method = RequestMethod.GET)
public String getSummary(Model model, HttpServletRequest request,
                                             HttpServletResponse response,
                                             @ModelAttribute("dateFrom") String dateFrom,
                                             @ModelAttribute("dateTo") String dateTo) throws Exception {

    logger.debug("date=" + dateFrom + "TO date=" + dateTo);
    AuthParam authParam = (AuthParam) request.getSession().getAttribute("authParam");
    if (authParam == null) {
        model.addAttribute("success", false);
        model.addAttribute("error_msg", "Auth Failed.");
        return "shipment/getSummary";
    }
    try {
        List<SummaryResponse> summaryBeanResponse = reportClient.getSummary(authParam, dateFrom, dateTo);
        logger.debug("Result List Size : {}", summaryBeanResponse.size());
        if (summaryBeanResponse.size() > 0) {
            byte[] reportBytes = buildSummaryXlsx(summaryBeanResponse, dateTo);
            logger.debug("Xlsx Sheet Generated!!");
            String fileName = "summary_" + StringUtils.join(dateTo.split("-"), "_") + ".xlsx";
            model.addAttribute("success", true);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("content-disposition", "attachment; filename=" + fileName);
            logger.debug("Content-Type : {}", response.getContentType());
            logger.debug("Header : {}", response.getHeader("Content-Disposition"));
            response.getOutputStream().write(reportBytes);
            logger.debug("Set ALL");
        } else {
            model.addAttribute("success", false);
            model.addAttribute("error_msg", "No data found by search.");
        }
    } catch (Exception ex) {
        model.addAttribute("success", false);
        model.addAttribute("error_msg", "Service error.");
        logger.error("ERROR on report xlsx", ex);
    }
    return "shipment/getSummary";
}

private byte[] buildSummaryXlsx(List<SummaryResponse> summaryResponseList, String date) throws Exception {
    try {
        Workbook workbook = new XSSFWorkbook();
        // create excel xls sheet
        XSSFSheet sheet = (XSSFSheet) workbook.createSheet("summary");
        sheet.setDefaultColumnWidth(14);

        // create style for header cells
        XSSFCellStyle headerStyle = (XSSFCellStyle) workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontName("Arial");
        headerStyle.setFont(font);
        headerStyle.setAlignment(HorizontalAlignment.CENTER);
        headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        int rowCount = 0;
        int cellCount = 0;

        // Manipulating Data Using Apache-POI

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    } catch (Exception ex) {
        logger.debug("Exception On Population Xlsx Sheet, {}", ex);
    }
    return null;
}

这是jsp视图名称​​ getSummary.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Get Xlsx report</title>
    <script type="text/javascript">
        $(document).ready(function () {
            var isSuccess = ${success};
            if (isSuccess == false) {
                var msg = "${error_msg}";
                alertify.alert(msg, function() {
                    window.location = "<%= request.getContextPath() %>/shipment/view.html";
                });
            }
        });
    </script>
</head>
<body>
${error_msg}
</body>
</html>

我正在设置内容类型,但响应标题看起来像

**Response Headers**
HTTP/1.1 200 OK
Cache-Control: no-cache
Cache-Control: no-store
Date: Mon, 31 Jul 2017 12:26:12 GMT
Pragma: no-cache
Transfer-Encoding: chunked
Content-Type: text/html;charset=UTF-8
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Content-Disposition: attachment; filename=summary_2017_07_31.xlsx
Set-Cookie: JSSESSIONID=1501503972634; path=/
Content-Language: en

印刷日志:

    2017-07-31 18:26:12,635 DEBUG [admin] (ShipmentController.java:522) - REPORT date=2017-07-1TO date=2017-07-31
    2017-07-31 18:26:12,635 DEBUG [admin] (ReportServiceClient.java:178) - Calling [ReportService.getSummary] service for dateFrom[2017-07-1] and dateTo[2017-07-31]
    2017-07-31 18:26:12,671 DEBUG [admin] (ShipmentController.java:531) - Result List Size : 4
    2017-07-31 18:26:12,824 DEBUG [admin] (ShipmentController.java:534) - Xlsx Sheet Generated!!
    2017-07-31 18:26:12,824 DEBUG [admin] (ShipmentController.java:539) - Content-Type : application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    2017-07-31 18:26:12,824 DEBUG [admin] (ShipmentController.java:540) - Header : attachment; filename=summary_2017_07_31.xlsx
    2017-07-31 18:26:12,824 DEBUG [admin] (ShipmentController.java:542) - Set ALL

我可以下载xlsx文件,但数据已损坏。实际上,网页内容/ html页面视图是用xlsx文件编写的。

当没有数据时我想显示弹出窗口,当有数据时我想下载创建的xlsx。

为什么设置后内容类型会发生变化。 我怎样才能妥善解决这个问题。

NB: 我有一个类似的控制器方法,我创建一个pdf文件并将内容类型设置为response.setContentType("application/pdf") 它对我来说很好。

1 个答案:

答案 0 :(得分:1)

您需要添加一个单独的控制器@RequestMapping,它只返回XLSX文件字节,注释为@ResponseBody。然后,您可以在JSP的主体内创建指向此端点的超链接,以便在用户单击它时,可以下载该文件。尝试在单个RequestMapping中返回JSP正文和XLSX内容是不行的,因为包含JSP的返回类型设置为text/html