2

I am exporting my database data to an excel sheet using spring boot. I am able to create and download the excel sheet in my browser but i am unable to send that excel file in my Response Entity .When I send my excel download url through postman I am getting some raw responses ,how can I can convert it so that it displays the contents of the file to the client. Here is my code. Can you please suggest me where i am doing wrong.

here is my service class which generate excel and store it in byte array.

    public byte[] exportToExcelFile() throws IOException {
    List<Employee> list = dao.getEmployee();

      XSSFWorkbook workbook = new XSSFWorkbook(); 
      XSSFSheet sheet = workbook.createSheet("Employee");
      XSSFRow row = sheet.createRow(1);

    // create style for header cells
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontName("Arial");
        style.setFillForegroundColor(HSSFColor.BLUE.index);
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font.setColor(HSSFColor.WHITE.index);
        style.setFont(font);

      // create header row
      XSSFRow header = sheet.createRow(0);

        header.createCell(0).setCellValue("sl nO");
        header.getCell(0).setCellStyle(style);

        header.createCell(1).setCellValue("Name");
        header.getCell(1).setCellStyle(style);

        header.createCell(2).setCellValue("Email");
        header.getCell(2).setCellStyle(style);

        header.createCell(3).setCellValue("Salary");
        header.getCell(3).setCellStyle(style);
        int rowCount = 1;

        for (Employee emp : list) {
            XSSFRow  aRow = sheet.createRow(rowCount++);
            aRow.createCell(0).setCellValue(emp.getId());
            aRow.createCell(1).setCellValue(emp.getName());
            aRow.createCell(2).setCellValue(emp.getEmail());
            aRow.createCell(3).setCellValue(emp.getSalary());
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            workbook.write(bos);
        } finally {
            bos.close();
        }
        byte[] bytes = bos.toByteArray();
       // FileOutputStream out = new FileOutputStream(new File("employee.xlsx"));
         //workbook.write(out);
          //out.close();
          System.out.println("exceldatabase.xlsx written successfully");
        return bytes;
}

here is my rest controller to download excel.

@RestController
public class MyController {
@Autowired
EmployeeService service;

@GetMapping(value = "/exportExcel")
public ResponseEntity exportEmployeeExcel(HttpServletResponse response) throws IOException {
    byte[] excelContent = service.exportToExcelFile();
    if (excelContent.length != 0) {

        response.setContentType("application/ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=myfile.xls");

        return new ResponseEntity(excelContent, HttpStatus.OK);

    } else {

        return new ResponseEntity("download fail", HttpStatus.NO_CONTENT);
    }
}

}

1 Answer 1

1

Could you try this :

@CrossOrigin
@ResponseBody
@GetMapping(value = "/exportExcel")
public ResponseEntity<InputStreamResource> exportEmployeeExcel(HttpServletResponse response) throws IOException {
        byte[] excelContent = service.exportToExcelFile();
    if (excelContent.length != 0) {
        String fileName = "example.xlsx";
            MediaType mediaType = MediaType.parseMediaType("application/vnd.ms-excel");
            File file = new File(fileName);
            FileUtils.writeByteArrayToFile(file, excelContent);
            InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

            return ResponseEntity.ok()
                    // Content-Disposition
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName())
                    // Content-Type
                    .contentType(mediaType)
                    // Contet-Length
                    .contentLength(file.length()) //
                        .body(resource);
        }else{
            return null; // you can return what you want !
        }

}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your response. I have tried the above code in my application. I am using FileUtils class of org.apache.tomcat.util.http.fileupload.FileUtils. but the method writeByteArrayToFile(file,byte[]) throwing error in my application saying The method writeByteArrayToFile(File, byte[]) is undefined for the type FileUtils.
kindly suggest me how to overcome this error. thanks in advance.
Sorry , I have added the wrong jar file i.e org.apache.tomcat.util.http.fileupload.FileUtils . Later I have corrected that to org.apache.commons.io.FileUtils and run the application. my excel file is downloaded bt when i fire the request on postman in the response i am getting some raw data instead of excel file.so How I will get that as I want to return the excel in rest api.
@LipsaPatra Well done of course you have to use org.apache.commons.io.FileUtils, Can you tag your question answered ?
I am unable get excel file in my rest api. I am able to generate excel file but in my rest controller i am unable to provide that excel file to the front end. How Could I achieve that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.