EasyExcel export large files

Project scenario:

springboot + nacos + mybatis:

In order to allow users to extract the required data in the database according to their own needs, the product manager defines the sql template, and realizes data export and download through the program


Problem Description

大文件导出 导致内存飙升


solution:

EasyExcel is a Java-based, fast, concise Excel processing tool that solves the memory overflow of large files.
It allows you to quickly complete functions such as reading and writing Excel without considering factors such as performance and memory.

主要代码如下:

public static void main(String[] args) {
    
    
    String path = "F:\\importFile\\";
    String filePath = "importDataFile.xlsx";
    //创建sheet
    WriteSheet writeSheet = EasyExcel.writerSheet(filePath).build();
    //列明(动态头部)
    List<List<String>> heads = new ArrayList<>();
    List<String> h1 = new ArrayList<>();
    h1.add("a1");
    heads.add(h1);
    File file = new File(path);
    if (!file.exists()) {
    
    
        file.mkdirs();
    }
    //内容(导入到excel,一个sheet不能超过104万)
    List<List<String>> res = new ArrayList<>();
    List<String> res1 = new ArrayList<>();
    res1.add("a");
    List<String> res2 = new ArrayList<>();
    res2.add("a2");
    res.add(res1);
    res.add(res2);
    ExcelWriter excelWriter = EasyExcel.write(path + filePath).head(heads).build();
    if (!new File(path + filePath).exists()) {
    
    
        //如果文件为空,先生成一个文件
        EasyExcel.write(path).sheet(filePath).doWrite(null);
        EasyExcel.write(path).head(heads).build();
    }
    if (!StringUtil.isEmpty(res) && null != excelWriter) {
    
    
        //写入内容(这一步可以放入循环中执行,可以减少 数据存储造成的内存问题)
        excelWriter.write(res, writeSheet);
    }
    //一定记得有这一步
    excelWriter.finish();
}

You can also refer to the example of the official website: official website link

Guess you like

Origin blog.csdn.net/u012129030/article/details/126312303