使用EasyExcel填充列表

147 阅读1分钟

1.Maven导入依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.1.0</version>
</dependency>

2. 定义模板文件

public static void main(String[] args) {
    // 模版文件保存地址
    File templateFileName = new File("D:\upload\templateFile.xlsx");
}

3. 定义模板样式和内容

public static void main(String[] args) {
    // 模板文件保存地址
    File templateFileName = new File("D:\upload\templateFile.xlsx");

    //模板样式
    WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
    // 内容水平对齐方式
    contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
    // 内容垂直对齐方式
    contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
    HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
    // 标题行高 内容行高
    SimpleRowHeightStyleStrategy rowHeightStrategy = new SimpleRowHeightStyleStrategy((short) 31, (short) 29);
    // 列宽
    SimpleColumnWidthStyleStrategy columnWidthStyleStrategy = new SimpleColumnWidthStyleStrategy(20);
    // 模板标题
    List<String> headerList = Stream.of("姓名", "数字").collect(Collectors.toList());
    List<List<String>> header = headerList.stream().map(item -> new ArrayList<>(Collections.singletonList(item))).collect(Collectors.toList());

    // 模板列
    List<String> column = Stream.of("{.name}", "{.number}").collect(Collectors.toList());
    List<List<String>> templateColumn = column.stream().map(item -> new ArrayList<>(Collections.singletonList(item))).collect(Collectors.toList());
    
    // 向模板文件填充标题和列
    EasyExcel.write(templateFileName.getPath())
            .registerWriteHandler(rowHeightStrategy)
            .registerWriteHandler(columnWidthStyleStrategy)
            .registerWriteHandler(horizontalCellStyleStrategy).head(header)
            .sheet().doWrite(templateColumn);
}

模板生成内容

image.png

4. 根据模板填充数据

//向模版填充数据
List<Map<String,String>> data = new ArrayList<>();
// 循环两次
for (int i = 0; i <= 2; i++){
    Map<String, String> map = new HashMap<>();
    map.put("name","张三");
    map.put("number","12");
    data.add(map);
}
// 模版文件保存地址
File fileName = new File("D:\upload\testFile.xlsx");
// 开始填充列表数据
EasyExcel.write(fileName.getPath()).inMemory(true).withTemplate("D:\upload\templateFile.xlsx").sheet().doFill(data);

填充完毕内容

image.png

本次主要记录EasyExcel模板填充,填充所使用的.inMemory(true)方法在大量数据填充时请不要使用,所有的数据都会在内存容易OOM,具体可以查看API官方说明。