如何使用Spring响应下载excel文件

时间:2016-07-01 09:18:56

标签: javascript java excel spring jasper-reports

我尝试使用Jasper Report 6.2.2下载excel文件

这是我的Spring Controller:

equalTo()

这里也是我的downloadReportFile方法代码:

@RequestMapping(value = "/downloadExcel", method = RequestMethod.POST)
    @ResponseBody
    public void downloadMyReportExcelFile(@RequestBody ExcelFilter excelFilter, HttpServletResponse response) {
        try {

            reportExportBo.downloadReportFile(response, excelFilter);


        } catch (Throwable e) {
            LOGGER.error("Unknown error at REST Service", e);
        }
    }

my_reports.jrxml适用于myObjectList,列和变量相同。

这也是我的javascript函数;

    @Override
        public void downloadReportFile(HttpServletResponse response, ExcelFilter excelFilter) {

            List<myClassObject> myObjectList= objectRecordBo.myData(excelFilter);

            InputStream is = this.getClass().getClassLoader().getResourceAsStream("/my_reports.jrxml");

            ExcelExporter exporter = new ExcelExporter();

            String fileName = "my_exported_report.xls";

            JasperDesign jd = JRXmlLoader.load(is);
            JasperReport jr = JasperCompileManager.compileReport(jd);

            JasperPrint jprint = JasperFillManager.fillReport(jr, null, new JRBeanCollectionDataSource(myObjectList));

            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            JRXlsExporter xlsExporter = new JRXlsExporter();
            xlsExporter.setExporterInput(new SimpleExporterInput(jprint));
            xlsExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));

            SimpleXlsReportConfiguration xlsReportConfiguration = new SimpleXlsReportConfiguration();
            xlsReportConfiguration.setOnePagePerSheet(false);
            xlsReportConfiguration.setRemoveEmptySpaceBetweenRows(true);
            xlsReportConfiguration.setDetectCellType(false);
            xlsReportConfiguration.setWhitePageBackground(false);
            xlsExporter.setConfiguration(xlsReportConfiguration);

            xlsExporter.exportReport();

调用downloadService方法后,我下载了Excel,但它不可读

enter image description here

我错了什么?

编辑:

顺便说一句,当我在html端使用时;

function downloadService(url, paramData, fileName, $http) {

return $http.post(url, paramData, {responseType:'Content-Type'}).then(function (response) {
    var blob = new Blob([response.data], {type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
    var objectUrl = URL.createObjectURL(blob);
    var a = document.createElement("a");
    a.style = "display: none";
    a.href = objectUrl;
    a.download = fileName + '.xls' ;
    document.body.appendChild(a);
    a.click();
    setTimeout(function () {
        document.body.removeChild(a);
        window.URL.revokeObjectURL(objectUrl);
    }, 100);
}, function (response) {
    //TODO
    });
}

和Spring控制器是GET,没有任何@RequestBody,它工作正常。但是我需要使用JSON Object传递参数,所以我不能使用它。

2 个答案:

答案 0 :(得分:2)

我解决了我的问题。

首先我在JasperDesign之前设置了Header和Content Type of Response。

...
if (list != null && list.size() > 0) {
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

                JasperDesign jd = JRXmlLoader.load(reportStream);
                JasperReport jr = JasperCompileManager.compileReport(jd);
...

我还更新了我的ajax服务;

...
return $http.post(newUrl, paramData, {responseType: 'arraybuffer'}).then(function (response) {
            var blob = new Blob([response.data], {type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8'});
....

感谢帮助家伙...

答案 1 :(得分:0)

这是另一个解决方案(javascript方面)可能对其他人有用:

        var request = new XMLHttpRequest();
        request.open('POST', url, true); // update the url
        request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
        request.responseType = 'blob';

        var fileName = "simulation_results.xlsx"; // file name
        request.onload = function (e) {
            if (this.status === 200) {
                var blob = this.response;
                if (window.navigator.msSaveOrOpenBlob) {
                    window.navigator.msSaveBlob(blob, fileName);
                } else {
                    var downloadLink = window.document.createElement('a');
                    var contentTypeHeader = request.getResponseHeader("Content-Type");
                    downloadLink.href = window.URL.createObjectURL(new Blob([blob], {
                        type: contentTypeHeader
                    }));
                    downloadLink.download = fileName;
                    document.body.appendChild(downloadLink);
                    downloadLink.click();
                    document.body.removeChild(downloadLink);
                }
            }
        };
        request.send(JSON.stringify(data)); // request data