1

I'm trying to download excel file by using Jasper Report 6.2.2

Here is my Spring Controller:

@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);
        }
    }

and also here is my downloadReportFile method codes:

    @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();

my_reports.jrxml is suitable for myObjectList, columns and variables are same.

Also here is my javascript function;

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
    });
}

After calling downloadService method, i got excel downloaded but it is not readable

enter image description here

What do i wrong?

EDITED:

By the way when i'm using in html side;

<a style="float:right; " href="service/downloadExcel">{{ 'EXPORT_EXCEL' | translate}}</a>

and Spring controller is GET and no any @RequestBody, it works fine. But I need to pass parameters with JSON Object, so i can not use it.

Süleyman K
  • 309
  • 1
  • 8
  • 17

2 Answers2

2

I solved my problem.

First I set Header and Content Type of Response, before JasperDesign.

...
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);
...

Also I updated my ajax service as;

...
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'});
....

Thanks for helping guys...

Süleyman K
  • 309
  • 1
  • 8
  • 17
1

Here is the another solution(javascript side) might be helpful for others:

        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
Satya J
  • 9
  • 2