首页 > 解决方案 > 使用spring的Jasper报告:文件格式和扩展名不匹配xls

问题描述

我在 Spring mvc 上有测试应用程序,用于使用 JasperReports 进行报告,我的代码是这样的:

        response.addHeader("Content-disposition", "attachment; filename=" + "testExcel.xls");
        response.setContentType("application/vnd.ms-excel");
        ServletOutputStream outputStream=response.getOutputStream();
        ServletContext context = request.getServletContext();
          String filename = "/WEB-INF/resources/jasperReports/testExcel.jasper";
          Map<String,Object> params = new HashMap<>();
          List<Customer>  listCustomer = service.listDataSource();
          JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(listCustomer);
            try {
                InputStream is = context.getResourceAsStream(filename);
                if (is != null) {
                    JasperReport report = JasperCompileManager.compileReport(is);
                    JasperPrint jasperPrint = JasperFillManager.fillReport(report, params, dataSource);
                    JRXlsExporter exporterXLSX = new JRXlsExporter();
                    exporterXLSX.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
                    exporterXLSX.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
                    exporterXLSX.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
                    exporterXLSX.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
                    exporterXLSX.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, outputStream);
                    exporterXLSX.exportReport();
                    is.close();
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (JRException exp) {
                exp.printStackTrace();
            } 

并且报告生成但由于错误而无法打开:文件格式和扩展名不匹配 testExcel.xls 出了什么问题我不明白。dataSource 很好,因为我使用它成功生成了 pdf。

标签: javaspring-mvcservletsjasper-reports

解决方案


推荐阅读