Failed to load Excel spreadsheet with output data from backend

REST method to return outputStream data to load an Excel spreadsheet:

@RequestMapping(value = "/downloadxls", method = RequestMethod.GET)
public @ResponseBody void getRecordsAndExportExcel(@RequestParam("search_param") String students, HttpServletResponse response) {
    response.setContentType("application/vnd.ms-excel");

 Workbook hssfWorkbook = exportExcelService.getExcelStudents(students);
        try {
            OutputStream out = response.getOutputStream();
            hssfWorkbook.write(out);
            out.flush();
            out.close();

        } catch (IOException e) {
           logger.error("Error exporting to excel:" + e); 
        }
}

I receive data as bytes, but in Angular I try to present it as an Excel table; but it will not load. I am doing this to convert:

var blob = new Blob([result.data],  {type : 'application/vnd.openxmlformats-officedocument.presentationml.presentation;charset=UTF-8'});
         FileSaver.saveAs(blob, "MyData.xls");

Request and response headers:

Access-Control-Allow-Headers:x-requested-with, content-type
Access-Control-Allow-Methods:GET OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600
Content-Type:application/vnd.ms-excel;charset=UTF-8
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
X-Application-Context:application:8080

Request header

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,ms;q=0.6
Connection:keep-alive
Host:localhost:8080
Origin:http://localhost:9000
Referer:http://localhost:9000/

I am making a GET call from the interface using Angular and calling the backend to load the data as an Excel spreadsheet, but it is not able to convert the output stream to blob / excel. How can I present an Excel spreadsheet as a download?

+4
source share
1 answer

, excel , - + excel, , , angular .

ExportExcel response = new ExportExcel();
response.setPath(excelPath);
return response;

Response response = excelService.generateExcel();
return new ResponseEntity<>(response, HttpStatus.OK);

angular:

if(response.status === 200){
var excelPath = response.data.path;
var win = window.open(excelPath, '_blank');
if (win) {
        //Browser has allowed it to be opened
        win.focus();
} else {
        //Browser has blocked it
        swal(   
            "Error!",   
           'Please allow popups for this website',   
           "error"
        );
    }                        
}

, .

0

Source: https://habr.com/ru/post/1655747/


All Articles