EasyExcel 模板+公式填充

使用 CellWriteHandler 的实现类来实现公式写入

复制代码
@Data
@NoArgsConstructor
public class CustomCellWriteHandler implements CellWriteHandler {

    private int maxRowNum = 2000;

	// 动态传入列表数量
    public CustomCellWriteHandler(int maxRowNum) {
        this.maxRowNum = maxRowNum;
    }

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        CellWriteHandler.super.afterCellDispose(context);
        // 可获取 sheetNo 或 sheetName 用于判断
        // Integer sheetNo = context.getWriteSheetHolder().getSheetNo();
        Cell cell = context.getCell();
        //行
        int rowNum = cell.getRowIndex();
        //列
        int columnNum = cell.getColumnIndex();
		// 对第3行第3列的单元格进行替换,设置为公式
        if (rowNum == 2 && columnNum == 2) {
            cell.setCellFormula("SUM(C4:C" + maxRowNum + ")");
        }
    }
}

注册填充

复制代码
// 构建导出表文件
ClassPathResource classPathResource = new ClassPathResource("excel_template/BaseInfoExport.xls");
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(classPathResource.getInputStream()).
		excelType(ExcelTypeEnum.XLS).autoCloseStream(Boolean.FALSE).build();
Map<String, Object> map = MapUtils.newHashMap();
// 在 fill 中必须要添加对应的模板,否则会变为空白
map.put("summary", "");
// 构造导出配置
WriteSheet writeSheet = EasyExcel.writerSheet(5).registerWriteHandler(new CustomCellWriteHandler(dataList.size() + 3)).build();
// 执行填充,先填充 dataList,再填充 map
excelWriter.fill(dataList, writeSheet);
excelWriter.fill(map, writeSheet);
excelWriter.finish();

注意 :如果使用了 FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();

会动态添加新行。如果先填充了 map 再填充列表,会把 map 填充的公式给拉长,导致填充位置与输入不一致。可以先填充列表,再填充 map。

注意2:此方法对 xls 格式的文件有效,对 xlsx 的不生效,能输出公式但不会自动计算。

相关推荐
开心香辣派小星5 小时前
23种设计模式-15解释器模式
java·设计模式·解释器模式
Halo_tjn5 小时前
虚拟机相关实验概述
java·开发语言·windows·计算机
摆烂z6 小时前
Docker与Jib(maven插件版)实战
java
RainbowSea6 小时前
从 Spring Boot 2.x 到 3.5.x + JDK21:一次完整的生产环境迁移实战
java·spring boot·后端
笨手笨脚の6 小时前
Spring Core常见错误及解决方案
java·后端·spring
奶油松果6 小时前
Springboot自动装配 - redis和redission
java·spring boot·redis
霍夫曼6 小时前
UTC时间与本地时间转换问题
java·linux·服务器·前端·javascript
VX:Fegn08957 小时前
计算机毕业设计|基于Java人力资源管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端·课程设计
荔枝hu7 小时前
springboot和shiro组合引入SseEmitter的一些坑
java·spring boot·后端·sseeitter
老华带你飞7 小时前
健身房|基于springboot + vue健身房管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端