【2023】Use alibaba’s easyexcel framework to implement excel tables and QR code downloads (simple, efficient, no redundant code, all with comments)

basic introduction

The more famous frameworks for generating Excel include Apache poi and jxl. But they all have a serious problem, which is that they consume a lot of memory. POI has a set of SAX mode APIs that can solve some memory overflow problems to a certain extent, but POI still has some flaws, such as the decompression and storage of the 07 version of Excel. It is done in memory, and memory consumption is still very large. easyexcel has rewritten poi's analysis of the 07 version of Excel. It can reduce the original 3M excel to use POI sax, which still requires about 100M of memory, to the KB level, and no matter how large the excel is, there will be no memory overflow. The 03 version relies on POI's sax mode. The model conversion is encapsulated in the upper layer to make it easier and more convenient for users. Alibaba's easyexcel is further encapsulated on this basis, making it more operable.

1. Add dependencies

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
          <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.4.0</version>
        </dependency>
        <!--二维码需要使用到的-->
                  <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.4.1</version>
        </dependency>
	<!--阿里巴巴easyexcel工具-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.1.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel-core</artifactId>
            <version>3.1.1</version>
        </dependency>

2. excel template

For export call
templates, the interpolation of ordinary variables is through {var}, and the list is {.var}.
Insert image description here

3. Model entity class

@Data
public class DeliverCardVO {
    
    
    private String workOrderCode;
    private byte[] qrCode;
    private String productCode;
    private String productName;
}

3.5, Controller specific implementation code

For simplicity and convenience in theory, they are not written separately. During the actual development process, part of the code can be encapsulated into tool classes for easy calling;

@RestController
@RequestMapping("/token")
public class BasicController {
    
    



  @PostMapping("/qrCode")
    public void prCode(HttpServletResponse response){
    
    
        File file = new File("workOrder模板.xlsx");    //使用的模板(使用的相对地址)
       final String fileName = "workOrder";   //文件名
        try {
    
    
//         设置请求头
//              设置响应内容编码
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
//              使用 UTF-8 编码对文件名进行编码
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
            encodedFileName = encodedFileName.replace("+", "%20");  // 替换空格字符

            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName + ".xlsx");

//            lombok的资源关闭注解,可以在使用完毕时自动关闭
            @Cleanup ServletOutputStream outputStream = response.getOutputStream();
//              用来写入Excel的文件工具类,底层引用了POI实现
            @Cleanup("finish") ExcelWriter excelWriter = EasyExcel.write(outputStream)
                    .excelType(ExcelTypeEnum.XLSX)
                    .withTemplate(file).build();

//            配置sheet参数(因为是引用的模板,实际配置sheet名称不会生效,会使用的模板的名称)
            WriteSheet writeSheet = EasyExcel.writerSheet(0, "test01").build();

//              集合列表
            List<DeliverCardVO> list= new ArrayList<>();
            for (int i = 0; i < 10; i++) {
    
    
                DeliverCardVO deliverCardVO = new DeliverCardVO();
                deliverCardVO.setProductCode("100010A"+i);
                deliverCardVO.setProductName("张三"+i);
                deliverCardVO.setWorkOrderCode("1831783812A"+i);
//                添加二维码,把二维码转为byte[]
                byte[] qrCode = QrCodeUtil.generatePng(deliverCardVO.getProductCode() + "-" + deliverCardVO.getWorkOrderCode(),
                        QrConfig.create().setCharset(Charset.forName("GBK")));
                deliverCardVO.setQrCode(qrCode);
                list.add(deliverCardVO);
            }
//              二维码配置类
            QrConfig qrConfig = QrConfig.create();
            qrConfig.setImg("D:\\1zheng\\test\\token\\mode01\\a1.jpg");  //设置二维码图片
            qrConfig.setCharset(Charset.forName("GBK"));  //设置编码
            qrConfig.setForeColor(new Color(115,155,208));  //设置前景色  依赖为(import java.awt.Color;)我这边默认引用的是另外一个路径的同名的,找了好一会原因
//            qrConfig.setBackColor(new Color(0,0,0));

            byte[] homepage = QrCodeUtil.generatePng("https://blog.csdn.net/weixin_52315708",qrConfig);  //添加二维码内容,可以为链接也可以是数据
                    
            HashMap<String, Object> map = new HashMap<>();
            map.put("date",new Date());
            map.put("sum",list.size());
            map.put("homepage",homepage);
//            添加普通遍历的值
            excelWriter.fill(map,writeSheet);

// 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行,然后下面的数据往后移动。默认 是false,会直接使用下一行,如果没有则创建。
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
//            添加列表的值
            excelWriter.fill(list,fillConfig ,writeSheet);
            excelWriter.finish();
        } catch (IOException e) {
    
    
            e.printStackTrace();

        }
    }
}

4. Use postman to test

The request header can be added when requesting, because it is a test, and the data is added directly by the backend.
Insert image description here

5. Realize the effect of the final printed EXCELD

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_52315708/article/details/131814241