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 的不生效,能输出公式但不会自动计算。

相关推荐
Wang's Blog6 小时前
Java框架 SpringCloud 快速入门: Eureka 服务发现与服务名调用改造
java·spring cloud·eureka
夕除6 小时前
redis--OpenResty
java·redis
Wang's Blog6 小时前
Java框架 SpringCloud 快速入门: Eureka 注册中心原理分析
java·spring cloud·eureka
她说彩礼65万6 小时前
C语言 assert
java·linux·c语言
vx-程序开发6 小时前
【计算机毕设】52744基于微信小程序的民宿智能预订系统
java·spring boot·毕业设计·源码·课程设计·毕设·大作业
Wang's Blog6 小时前
Java框架 SpringCloud 快速入门: Eureka 服务注册
java·spring cloud·eureka
liangshanbo12156 小时前
请求拦截器相关面试题
java·前端·javascript
她说彩礼65万7 小时前
C语言 const的使用
java·服务器·c语言
开开心心就好7 小时前
视频压缩工具推荐,绿色版免安装双击即用
java·前端·人工智能·spring·智能手机·intellij-idea·excel
Wang's Blog7 小时前
Java框架 SpringCloud 快速入门: Eureka 注册中心的搭建
java·spring cloud·eureka