提问者:小点点

无法在Spring引导Rest控制器的响应实体中获取excel文件


我正在使用Spring引导将我的数据库数据导出到excel工作表。我能够在浏览器中创建和下载excel工作表,但我无法在响应实体中发送该excel文件。当我通过postman发送我的excel下载URL时,我得到了一些原始响应,我如何才能将其转换为向客户端显示文件内容。这是我的代码。你能建议我哪里做错了吗?

这是我的服务类,它生成excel并将其存储在字节数组中。

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

这是我的Rest控制器下载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个答案

匿名用户

你能试试这个吗:

@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 !
        }

}