Excel file download using java - Error : File is corrupted

Viewed 316

I need to download an .xls file from src/main/resources/DAO folder in my spring boot project.

file name : DAOtemplate.xls

I wrote a code for that.

 @GetMapping("/downloadDOA")
    public ResponseEntity<Object>  downloadTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException{
   
        
        String filename = "C://Users//Sai//git//r5//src//main//resources//DOA//DOAtemplate.xls";
        File file = new File(filename);
        
        InputStreamResource iresource = new InputStreamResource(new FileInputStream(file));
        
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition","attachment;filename=" +file.getName());
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        ResponseEntity<Object> responseEntity = ResponseEntity.ok().headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/vnd.ms-excel")).body(iresource);

        return responseEntity;
        
    
        
    }

When I use the api the excel file is getting downloaded but the data inside the file is getting corrupted.

Here is a screenshot of the corrupted data.

enter image description here

Can anyone pls help me what changes need to be made?

0 Answers
Related