webflux 下载excel
方案1
public class DownloadUtil {
public static <T> Mono<Void> downloadExcel(List<T> data, Class<T> clz,String filename,ServerHttpResponse response) {
HttpHeaders headers = response.getHeaders();
headers.set(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=".concat(filename).concat(""));
MediaType application = new MediaType("application", "vnd.ms-excel", Charset.forName("UTF-8"));
headers.setContentType(application);
DefaultDataBuffer dataBuffer = new DefaultDataBufferFactory().allocateBuffer();
OutputStream outputStream = dataBuffer.asOutputStream();
EasyExcel.write(outputStream, clz).sheet("sheet1").doWrite(data);
Flux<DataBuffer> dataBufferFlux = Flux.create((FluxSink<DataBuffer> emitter) -> {
emitter.next(dataBuffer);
emitter.complete();
});
return response.writeWith(dataBufferFlux);
}
}
@GetMapping(value = "/download")
public Mono<Void> downloadDept(ServerHttpResponse response) {
List<ExportDto> result = departmentService.downloadDept(merchantCode);
return DownloadUtil.downloadExcel(result,ExportDto.class,"download.xlsx", response);
}
方案2
@GetMapping(value = "/downloadFile")
public Mono<Void> downloadTest(ServerHttpResponse response) {
File file = new File("test.xlsx");
FileInputStream in =null;
try {
in = new FileInputStream(file);
Flux<DataBuffer> dataBufferFlux = DataBufferUtils.readByteChannel(in::getChannel,new DefaultDataBufferFactory(),4096);
ZeroCopyHttpOutputMessage zeroCopyHttpOutputMessage = (ZeroCopyHttpOutputMessage)response;
HttpHeaders headers = zeroCopyHttpOutputMessage.getHeaders();
headers.set(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=test.xlsx");
MediaType application = new MediaType("application", "vnd.ms-excel", Charset.forName("UTF-8"));
headers.setContentType(application);
return zeroCopyHttpOutputMessage.writeWith(dataBufferFlux);
} catch (Exception e) {
e.printStackTrace();
}
return Mono.empty();
}