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

相关推荐
武昌库里写JAVA13 分钟前
JAVA面试汇总(四)JVM(一)
java·vue.js·spring boot·sql·学习
落霞的思绪1 小时前
Java设计模式详细解读
java·开发语言·设计模式
Java小白程序员1 小时前
Spring Framework:Java 开发的基石与 Spring 生态的起点
java·数据库·spring
拂晓银砾2 小时前
Java数据结构-栈
java·数据结构
甄超锋2 小时前
Java Maven更换国内源
java·开发语言·spring boot·spring·spring cloud·tomcat·maven
m0_719084112 小时前
sharding-jdbc读写分离配置
java
还是鼠鼠3 小时前
tlias智能学习辅助系统--Maven 高级-私服介绍与资源上传下载
java·spring boot·后端·spring·maven
Xiaokai丶3 小时前
Java 8 新特性深度剖析:核心要点与代码实战
java
灵魂猎手3 小时前
3. MyBatis Executor:SQL 执行的核心引擎
java·后端·源码
Galaxy在掘金3 小时前
从业8年,谈谈我认知的后端架构之路-1
java·架构