SpringWebflux框架里导出excel文档

本demo里使用springboot 2.7.0版本。

@GetMapping("/download/excel/file")
    public Mono<Void> downloadExcelFile(ServerHttpResponse response, WebSession webSession) {
        
        // 设置被下载的文件名称
        response.getHeaders().set(org.springframework.http.HttpHeaders.CONTENT_DISPOSITION, "attachment; " +
                            "filename=demo.xls");
        response.getHeaders().add("Accept-Ranges", "bytes");
        
        // 定义输出流
        DefaultDataBuffer dataBuffer = new DefaultDataBufferFactory().allocateBuffer();
                    OutputStream outputStream = dataBuffer.asOutputStream();
        try {
            // 定义excel文件
            Workbook workbook = new XSSFWorkbook();
            // 将excel文件流写入到output流
            workbook.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Flux<DataBuffer> dataBufferFlux = Flux.create((FluxSink<DataBuffer> emitter) -> {
                        emitter.next(dataBuffer);
                        emitter.complete();
                    });
        
        // 往response写output流
//                    return response.writeWith(dataBufferFlux);
        return response.writeAndFlushWith(Mono.just(dataBufferFlux));
    }

 end.

posted on 2022-08-19 17:39  梦幻朵颜  阅读(789)  评论(0编辑  收藏  举报