逐个发送excel文件

时间:2019-05-25 10:19:49

标签: excel spring spring-boot microservices

我正在尝试在两个微型计算机之间建立通信,其中第一个微型计算机接收前端的请愿书并与另一个微型计算机联系,这将创建一个excel文件并将其发送回第一个微型计算机,开始下载文件

首先,我尝试打印一个简单的String响应以检查micros之间的通讯,并且该通讯正常,但是文件的相同操作不起作用。

这是我要遵循的代码: 对于控制器A:


    @GetMapping(path="/test")
    public void getEntities2(HttpServletRequest request, HttpServletResponse response) throws IOException {   

        ResponseEntity<Workbook> responseEntity = new RestTemplate()
                .getForEntity("http://localhost:8080/proceso/excel", Workbook.class);
        assertThat(responseEntity.getStatusCode(), equalTo(HttpStatus.OK));
        response.setHeader("Content-disposition", "attachment; filename=" + "test.xls");
        Workbook workbook = responseEntity.getBody();
        workbook.write(response.getOutputStream());
        workbook.close();       
    }

第二个控制器(Excel文件生成器):


@GetMapping(path="/excel")
    public ResponseEntity<Workbook> test3(HttpServletResponse response) throws Exception {
        HashMap<String, ArrayList<String>> test = new HashMap<String, ArrayList<String>>();
        Workbook workbook =  CreateExcel.excelCreator(test);

        Workbook responseFile = workbook;
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + "test.xls")
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .body(responseFile);
    }


然后出现以下错误:

org.springframework.web.client.HttpClientErrorException$NotAcceptable: 406 null

我只想在第一个控制器中接收文件,然后从本地主机下载Excel。有什么办法吗?谢谢大家。

1 个答案:

答案 0 :(得分:0)

我发现了问题。 excel文件是一个八位字节流文件,因此需要以byte []数组的形式接收。这是控制器A:

    @GetMapping(path="/")
public ResponseEntity<byte[]> getEntities() throws IOException {   
ResponseEntity<byte[]> responseEntity = new RestTemplate()
.getForEntity("http://localhost:8080/excel", byte[].class);
assertThat(responseEntity.getStatusCode(), equalTo(HttpStatus.OK));

return responseEntity;
}

和控制器B:

@GetMapping(path="/excel")
public void getExcel(HttpServletResponse response) throws Exception {

Iterable<InstancesAggregate> list = instancesAggregate.myfindAll(); //Creating a list
HashMap<String, ArrayList<String>> test = CreateExcel.setExcelProceso(list);
Workbook workbook =  CreateExcel.excelCreator(test);
response.setHeader("Content-disposition", "attachment; filename=" + "test.xls");
   workbook.write(response.getOutputStream());
   workbook.close();    

}

这对我来说很好,希望有人觉得有用。