小言_互联网的博客

手把手教你Spring WebFlux导出数据到excel中

491人阅读  评论(0)

常用组件:

WorkbookFactory excel的文档对象

Sheet excel的表单

Row excel的行

Cell excel的格子单元

Font excel字体

样式:

CellStyle cell样式

实现步骤:
1.添加maven依赖

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.9</version>
</dependency>

2.编写Controller
使用spring webflux文件下载就没有之前基于servlet容器的javax.servlet.http.HttpServletResponse了,取而代之的是org.springframework.http.server.reactive.ServerHttpResponse。

   @GetMapping("/cars/download/{carId}")
    public Mono<Void> downloadByWriteWith(ServerHttpResponse response, @PathVariable("carId") String carId) throws IOException {
   
        return manager.downloadByWriteWith(response, carId);
    }

3.编写Manager

public Mono<Void> downloadByWriteWith(ServerHttpResponse response, String carId)
            throws IOException {
   
        //spring webflux文件下载零拷贝(Zero-copy)
        ZeroCopyHttpOutputMessage zeroCopyResponse = (ZeroCopyHttpOutputMessage) response;
        //设置文件下载响应头
        response.getHeaders().set(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=car.xlsx");
        response.getHeaders().setContentType(MediaType.APPLICATION_OCTET_STREAM);

        return getCar(carId).flatMap(x -> getCarModel(x)).flatMap(s -> {
   
            try {
   

                String relTarget = "/static/car.xlsx";
                //声明输入流
                InputStream inputStream = null;
                //声明输出流
                OutputStream fout = null;
                //声明临时文件
                File targetFile = null;
                // getResourceAsStream不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从ClassPath根下获取。其只是通过path构造一个绝对路径,最终还是由ClassLoader获取资源。
                inputStream = this.getClass().getResourceAsStream(relTarget);
                //创建临时文件(在默认临时文件目录中创建一个空文件,使用给定前缀和后缀生成其名称。)
                targetFile = File.createTempFile("car", "");
                //excel的文档对象(WorkbookFactory)
                final Workbook wb = WorkbookFactory.create(inputStream);//WorkbookFactory可以读取xls格式或xlsx格式
                //获取该工作区的第一个sheet
                Sheet sheet = wb.getSheetAt(0);
                //创建样式类
                CellStyle cellStyle = wb.createCellStyle();
                // 设置自动换行
                cellStyle.setWrapText(true);
                // 水平居中
                cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                // 垂直居中
                cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
                // 设置字体
                Font font = wb.createFont();
                font.setFontName("仿宋_GB2312");
                // 设置字体粗细
                font.setBoldweight(HSSFFont.DEFAULT_CHARSET);
                // 设置字体大小
                font.setFontHeightInPoints((short) 14);
                // 选择需要用到的字体格式
                cellStyle.setFont(font);
                // 设置边框
                cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
                cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
                cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
                cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
                String departmentName = Optional.ofNullable(s.getDepartmentName()).orElse("");
                String applicantName = Optional.ofNullable(s.getApplicantName()).orElse("");
                String drivingTime = Optional.ofNullable(s.getDrivingTime()).map(x -> DateUtils.dateFormat(DateUtils.sdfTimeDate, x)).orElse("");
                String reason = Optional.ofNullable(s.getReason()).map(x -> x + "\n时间:" + drivingTime).orElse("");
                String license = Optional.ofNullable(s.getLicense()).orElse("");
                String destination = Optional.ofNullable(s.getDestination()).orElse("");
                String people = Optional.ofNullable(s.getPeople()).map(String::valueOf).map(x -> x + "(人)").orElse("");
                String days = Optional.ofNullable(s.getDays()).map(String::valueOf).map(x -> x + "(天)").orElse("");
                String pickTime = Optional.ofNullable(s.getPickTime()).map(x -> DateUtils.dateFormat(DateUtils.sdfTimeDate, x)).orElse("");
                String pickAutograph = Optional.ofNullable(s.getPickAutograph()).map(String::valueOf).orElse("");
                String firstApprovalName = Optional.ofNullable(s.getFirstApproval()).map(x -> x.getApprovalName() + " <====> " + (x.getApprovalStatus() == 1 ? "未审" : x.getApprovalStatus() == 2 ? "同意" : "拒绝")).orElse("无");
                String secondApprovalName = Optional.ofNullable(s.getSecondApproval()).map(x -> x.getApprovalName() + " <====> " + (x.getApprovalStatus() == 1 ? "未审" : x.getApprovalStatus() == 2 ? "同意" : "拒绝")).orElse("无");
                String threeApprovalName = Optional.ofNullable(s.getThreeApproval()).map(x -> x.getApprovalName() + " <====> " + (x.getApprovalStatus() == 1 ? "未审" : x.getApprovalStatus() == 2 ? "同意" : "拒绝")).orElse("无");
                String returnTime = Optional.ofNullable(s.getReturnTime()).map(x -> DateUtils.dateFormat(DateUtils.sdfTimeDate, x)).orElse("");
                String returnKilometre = Optional.ofNullable(s.getReturnKilometre()).map(String::valueOf).orElse("");
                String returnAutograph = Optional.ofNullable(s.getReturnAutograph()).map(String::valueOf).orElse("");
                //设置该工作区的第一个sheet名字
                wb.setSheetName(0, "名字");
              
                Row row = sheet.getRow(1); //获取第二行(0开始)
                //设置第二行(0开始)第二列(0开始)的值和样式
                Cell cell = row.createCell(1);
                cell.setCellValue(departmentName);
                cell.setCellStyle(cellStyle);
                //设置第二行(0开始)第四列(0开始)的值和样式
                Cell cell1 = row.createCell(3);
                cell1.setCellValue(applicantName);
                cell1.setCellStyle(cellStyle);
                
                Row row1 = sheet.getRow(2);
                Cell cell2 = row1.createCell(1);
                cell2.setCellValue(reason);
                cell2.setCellStyle(cellStyle);
               
                Row row2 = sheet.getRow(3);
                Cell cell3 = row2.createCell(1);
                cell3.setCellValue(license);
                cell3.setCellStyle(cellStyle);
                Cell cell4 = row2.createCell(3);
                cell4.setCellValue(destination);
                cell4.setCellStyle(cellStyle);
                
                Row row3 = sheet.getRow(4);
                Cell cell5 = row3.createCell(1);
                cell5.setCellValue(people);
                cell5.setCellStyle(cellStyle);
                Cell cell6 = row3.createCell(3);
                cell6.setCellValue(days);
                cell6.setCellStyle(cellStyle);
               
                Row row4 = sheet.getRow(5);
                Cell cell7 = row4.createCell(1);
                cell7.setCellValue(pickTime);
                cell7.setCellStyle(cellStyle);
                Cell cell8 = row4.createCell(3);
                cell8.setCellValue(pickAutograph);
                cell8.setCellStyle(cellStyle);
                
                Row row5 = sheet.getRow(7);
                Cell cell9 = row5.createCell(1);
                cell9.setCellValue(firstApprovalName);
                cell9.setCellStyle(cellStyle);
                
                Row row6 = sheet.getRow(8);
                Cell cell10 = row6.createCell(1);
                cell10.setCellValue(secondApprovalName);
                cell10.setCellStyle(cellStyle);

                
                Row row7 = sheet.getRow(9);
                Cell cell11 = row7.createCell(1);
                cell11.setCellValue(threeApprovalName);
                cell11.setCellStyle(cellStyle);

                
                Row row8 = sheet.getRow(10);
                Cell cell12 = row8.createCell(1);
                cell12.setCellValue(returnTime);
                cell12.setCellStyle(cellStyle);
                Cell cell13 = row8.createCell(3);
                cell13.setCellValue(returnKilometre);
                cell13.setCellStyle(cellStyle);

                
                Row row9 = sheet.getRow(11);
                Cell cell14 = row9.createCell(1);
                cell14.setCellValue(returnAutograph);
                cell14.setCellStyle(cellStyle);

                //将临时文件输出
                fout = new BufferedOutputStream(new FileOutputStream(targetFile));
                //写入工作区
                wb.write(fout);
                //这里将数据写入ServerHttpResponse
                return zeroCopyResponse.writeWith(targetFile, 0, targetFile.length());
            } catch (Exception e) {
   
                throw new RuntimeException(e);
            }
        });

    }

4.测试
测试的话可以使用swagger或者postman,甚至你前端技术足够ok的话也可以写个简单的页面进行测试,我是用的是postman进行的测试,下面就是我测试的结果了:


转载:https://blog.csdn.net/qq_42322632/article/details/115704260
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场