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

相关推荐
糖炒栗子032612 小时前
图片加水印与 EXIF 保留方案
java
tongxh42312 小时前
Spring Boot问题总结
java·spring boot·后端
Chan1612 小时前
SpringAI:RAG 最佳实践与调优
java·spring boot·ai·java-ee·intellij-idea·rag·springai
odng12 小时前
Windsurf / Codex 默认只显示 3 个最近任务,如何改成 100 个
java
m0_7167652312 小时前
C++巩固案例--通讯录管理系统详解
java·开发语言·c++·经验分享·学习·青少年编程·visual studio
Predestination王瀞潞12 小时前
Java EE3-我独自整合(第三章:Spring DI 入门案例)
java·spring·java-ee
Ttang2312 小时前
Java爬虫:Jsoup+OkHttp实战指南
java·爬虫·okhttp
李庆政37012 小时前
OkHttp的基本使用 实现GET/POST请求 authenticator自动认证 Cookie管理 请求头设置
java·网络协议·http·okhttp·ssl
Chan1612 小时前
SpringAI:MCP 协议介绍与接入方法
java·人工智能·spring boot·spring·java-ee·intellij-idea·mcp
dllxhcjla12 小时前
苍穹外卖2
java