EasyExcel中自定义拦截器的运用

在EasyExcel中自定义拦截器不仅可以帮助我们不止步于数据的填充,而且可以对样式、单元格合并等带来便捷的功能。下面直接开始

我们定义一个MergeWriteHandler的类继承AbstractMergeStrategy实现CellWriteHandler

public class MergeLastWriteHandler extends AbstractMergeStrategy implements CellWriteHandler 

当中我们重写merge方法

@Overrideprotected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {}

我们可以在重写的方法中得到形参中的Cel,那我们可以通过调用cell.getStringCellValue()得到当前单元格的内容,判断当前单元格的内容是否是目标单元格,例如下面代码

if (cell.getStringCellValue().equals("说明")) {cell.setCellValue("说明:这是一条说明");//获取表格最后一行int lastRowNum = sheet.getLastRowNum();CellRangeAddress region = new CellRangeAddress(lastRowNum, lastRowNum, 0, 5);sheet.addMergedRegionUnsafe(region);}

并且这里我们通过sheet中的 getLastRowNum()获取最后一行,最终通过CellRangeAddress来进行单元格合并,从下面源码我们可以了解到合并的规则是什么(通过int firstRow, int lastRow, int firstCol, int lastCol)

/*** Creates new cell range. Indexes are zero-based.** @param firstRow Index of first row* @param lastRow Index of last row (inclusive), must be equal to or larger than {@code firstRow}* @param firstCol Index of first column* @param lastCol Index of last column (inclusive), must be equal to or larger than {@code firstCol}*/public CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol) {super(firstRow, lastRow, firstCol, lastCol);if (lastRow < firstRow || lastCol < firstCol) {throw new IllegalArgumentException("Invalid cell range, having lastRow < firstRow || lastCol < firstCol, " +"had rows " + lastRow + " >= " + firstRow + " or cells " + lastCol + " >= " + firstCol);}}

这样就可以实现合并单元格,不过这里可能会出现一个问题

java.lang.IllegalStateException: Cannot get a STRING value from a NUMERIC cellat org.apache.poi.xssf.streaming.SXSSFCell.typeMismatch(SXSSFCell.java:943)at org.apache.poi.xssf.streaming.SXSSFCell.getStringCellValue(SXSSFCell.java:460)

因为会访问所有的单元格,有可能会出现是不是字符串类型的单元格,所以我们最好在开始的时候对其进行处理一次

if (cell.getCellType().equals(CellType.NUMERIC)){double numericCellValue = cell.getNumericCellValue();String s = Double.toString(numericCellValue);String substring = s.substring(0, s.indexOf("."));cell.setCellValue(substring);}

但这里可能我们还需要一个操作,例如如果我们全局配置了表框线条,但是不想当前的单元格有线条,如何处理呢,定义CustomCellWriteHandler拦截器继承AbstractCellWriteHandler

public class CustomCellWriteHandler extends AbstractCellWriteHandler{}

重写当中的afterCellDispose方法,得到

 @Overridepublic void afterCellDispose(CellWriteHandlerContext context) {super.afterCellDispose(context);}

现在我们对其进行操作

  Cell cell = context.getCell();if(BooleanUtils.isNotTrue(context.getHead())){if(cell.getStringCellValue().contains("说明"))){Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();CellStyle cellStyle = workbook.createCellStyle();cellStyle.setBorderTop(BorderStyle.THIN);cellStyle.setBorderBottom(BorderStyle.THIN);cellStyle.setAlignment(HorizontalAlignment.LEFT);cell.setCellStyle(cellStyle);context.getFirstCellData().setWriteCellStyle(null); //关键代码,不设置不生效}
}

最后只需要在写入的时候,把拦截器放进去就可以了,看完整代码

public class CustomCellWriteHandler extends AbstractCellWriteHandler {@Overridepublic void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {short height = 600;row.setHeight(height);}@Overridepublic void afterCellDispose(CellWriteHandlerContext context) {Cell cell = context.getCell();if(BooleanUtils.isNotTrue(context.getHead())){if(cell.getStringCellValue().contains("说明"))){Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();CellStyle cellStyle = workbook.createCellStyle();cellStyle.setBorderTop(BorderStyle.THIN);cellStyle.setBorderBottom(BorderStyle.THIN);cellStyle.setAlignment(HorizontalAlignment.LEFT);cell.setCellStyle(cellStyle);context.getFirstCellData().setWriteCellStyle(null);}}super.afterCellDispose(context);}
}

合并单元格的拦截器

public class MergeLastWriteHandler extends AbstractMergeStrategy implements CellWriteHandler {public static HorizontalCellStyleStrategy getStyleStrategy() {// 头的策略WriteCellStyle headWriteCellStyle = new WriteCellStyle();// 设置对齐//headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);// 背景色, 设置为绿色,也是默认颜色headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());// 字体//WriteFont headWriteFont = new WriteFont();//headWriteFont.setFontHeightInPoints((short) 12);//headWriteCellStyle.setWriteFont(headWriteFont);// 内容的策略WriteCellStyle contentWriteCellStyle = new WriteCellStyle();// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定// contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);// 字体策略WriteFont contentWriteFont = new WriteFont();//contentWriteFont.setFontHeightInPoints((short) 12);contentWriteCellStyle.setWriteFont(contentWriteFont);//设置 自动换行contentWriteCellStyle.setWrapped(true);//设置 垂直居中contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//设置 水平居中contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);//设置边框样式contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);contentWriteCellStyle.setBorderTop(BorderStyle.THIN);contentWriteCellStyle.setBorderRight(BorderStyle.THIN);contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);return horizontalCellStyleStrategy;}@Overrideprotected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {if (cell.getCellType() == CellType.NUMERIC) {double numericCellValue = cell.getNumericCellValue();String s = Double.toString(numericCellValue);String substring = s.substring(0, s.indexOf("."));cell.setCellValue(substring);}if (cell.getStringCellValue().equals("说明")) {cell.setCellValue("说明:这是一条说明");//获取表格最后一行int lastRowNum = sheet.getLastRowNum();CellRangeAddress region = new CellRangeAddress(lastRowNum, lastRowNum, 0, 5);sheet.addMergedRegionUnsafe(region);}}
}

看一下Controller层

@GetMapping("/excelWrapper")public void excelWrapper(HttpServletResponse response) throws IOException {try {List<User> userList =  DataByExcel();  //获取数据的列表List<BudgetForm> budgetForm = BeanUtil.copyToList(userList,BudgetForm.class);String fileName = one.getProjectName() + ".xlsx";response.setContentType("application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet");response.setCharacterEncoding("utf-8");response.setHeader("Content-disposition", "attachment;filename=" + fileName );// 创建ExcelWriter对象WriteSheet writeSheet = EasyExcel.writerSheet("表格sheet").registerWriteHandler(new MergeLastWriteHandler()).registerWriteHandler(new CustomCellWriteHandler()).build();// 向Excel中写入数据ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), BudgetForm.class).build();excelWriter.write(userList , writeSheet);// 关闭流excelWriter.finish();} catch (Exception e) {e.printStackTrace();}}

对表头设置(自己对应表格设置对应字段)

@Data
@ContentRowHeight(47) //内容行高
@HeadRowHeight(35)//表头行高
public class BudgetForm implements Serializable  {@ColumnWidth(6)@ExcelProperty(value ={"表格","序号"} ,index = 0)@ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER)private Integer serialNumber;@ColumnWidth(15)@ExcelProperty(value ={"表格","名称"} ,index = 1)@ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER)private String name;@ColumnWidth(26)@ExcelProperty(value = {"表格","备注"},index = 2)@ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER)private String remark;@ColumnWidth(26)@ExcelProperty(value = {"表格","其他"},index = 3)@ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER)private String budgetary;@ExcelIgnore@ApiModelProperty("合计")private String total;}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/649936.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

openssl3.2/test/certs - 073 - CA-PSS

文章目录 openssl3.2/test/certs - 073 - CA-PSS概述笔记setup073.shsetup073_sc1.shsetup073_sc2.shsetup073_sc3.shsetup073_sc4.shsetup073_sc5.shEND openssl3.2/test/certs - 073 - CA-PSS 概述 openssl3.2 - 官方demo学习 - test - certs 这个官方脚本里面学到东西了,…

微信小程序(十八)组件通信(父传子)

注释很详细&#xff0c;直接上代码 上一篇 新增内容&#xff1a; 1.组件属性变量的定义 2.组件属性变量的默认状态 3.组件属性变量的传递方法 解释一下为什么是父传子&#xff0c;因为组件是页面的一部分&#xff0c;数据是从页面传递到组件的&#xff0c;所以是父传子&#xf…

防火墙的用户认证

目录 1. 认证的区别 2. 用户认证的分类 区别&#xff1a; 3. 上网用户认证的认证方式 3.1 置用户认证的位置&#xff1a; 3.1.1 认证域 创建认证域&#xff1a; 新建一个用户组&#xff1a; 新建一个用户 创建安全组 4. 认证策略 4.1 认证策略方式&#xff1a; 4.2…

MR image smoothing or filtering 既 FWHM与sigma之间的换算关系 fslmaths -s参数

这里写目录标题 FWHM核高斯核中的sigma是有一个换算公式&#xff1a;结果 大量的文献中都使用FWHM 作为单位&#xff0c;描述对MR等数据的平滑&#xff08;smoothing&#xff09;或者滤波&#xff08;filtering&#xff09;过程。FWHM 通常是指full width at half maximum的缩写…

yaml学习笔记

文章目录 yaml语言学习yaml 简介yaml 和json 区别基本语法数据类型YAML 对象YAML 数组锚点和引用纯量 参考文档 yaml语言学习 最近发现在学习k8s中各种配置文件 都是使用的yaml 这种格式, 包括 docker-compose.yaml 也都是用这个格式配置部署项目信息,我就了解了一下这个语法就…

字符串随机生成工具(开源)-Kimen(奇门)

由于最近笔者在开发数据脱敏相关功能&#xff0c;其中一类脱敏需求为能够按照指定的格式随机生成一个字符串来代替原有信息&#xff0c;数据看起来格式需要与原数据相同&#xff0c;如&#xff1a;电话号码&#xff0c;身份证号以及邮箱等。在网上搜索了下&#xff0c;发现没有…

【新书推荐】3.5 char类型

本节必须掌握的知识点&#xff1a; 示例十 代码分析 汇编解析 3.5.1 示例十 char类型是比较古怪的&#xff0c;int\short\long类型如果在使用时不指定signed还是unsigned时都默认是signed&#xff0c;但char不一样&#xff0c;编译器可以实现为带符号的&#xff0c;也可以实现…

洛谷B3621枚举元组

枚举元组 题目描述 n n n 元组是指由 n n n 个元素组成的序列。例如 ( 1 , 1 , 2 ) (1,1,2) (1,1,2) 是一个三元组、 ( 233 , 254 , 277 , 123 ) (233,254,277,123) (233,254,277,123) 是一个四元组。 给定 n n n 和 k k k&#xff0c;请按字典序输出全体 n n n 元组&am…

Flink实现数据写入MySQL

先准备一个文件里面数据有&#xff1a; a, 1547718199, 1000000 b, 1547718200, 1000000 c, 1547718201, 1000000 d, 1547718202, 1000000 e, 1547718203, 1000000 f, 1547718204, 1000000 g, 1547718205, 1000000 h, 1547718210, 1000000 i, 1547718210, 1000000 j, 154771821…

【QT】文件目录操作

目录 1 文件目录操作相关的类 2 实例概述 2.1 实例功能 2.2 信号发射者信息的获取 3 QCoreApplication类 4 QFile类 5 QFilelnfo类 6 QDir类 7 QTemporaryDir和QTemporaryFiIe 8 QFiIeSystemWatcher类 文件的读写是很多应用程序具有的功能&#xff0c;甚至某些应用程序就是围绕…

C语言赋值表达式中什么是左值和右值?数组名作为左右值时又具有怎样的意义?

一、问题 赋值表达式中可以分为左值和右值&#xff0c;那么什么是左值和右值&#xff1f;数组名做为左右值时又具有怎样的意义&#xff1f; 二、解答 在C语言中&#xff0c;左值和右值的概念对于理解赋值表达式以及程序的正确性非常重要&#xff1a; 1、左值 • 左值是一个…

内存管理(mmu)/内存分配原理/多级页表

1.为什么要做内存管理&#xff1f; 随着进程对内存需求的扩大&#xff0c;和同时调度的进程增加&#xff0c;内存是比较瓶颈的资源&#xff0c;如何更好的高效的利于存储资源是一个重要问题。 这个内存管理的需求也是慢慢发展而来&#xff0c;早期总线上的master是直接使用物…

Oracle篇—分区索引的重建和管理(第三篇,总共五篇)

☘️博主介绍☘️&#xff1a; ✨又是一天没白过&#xff0c;我是奈斯&#xff0c;DBA一名✨ ✌✌️擅长Oracle、MySQL、SQLserver、Linux&#xff0c;也在积极的扩展IT方向的其他知识面✌✌️ ❣️❣️❣️大佬们都喜欢静静的看文章&#xff0c;并且也会默默的点赞收藏加关注❣…

ES的一些名称和概念总结

概念 先看看ElasticSearch的整体架构&#xff1a; 一个 ES Index 在集群模式下&#xff0c;有多个 Node &#xff08;节点&#xff09;组成。每个节点就是 ES 的Instance (实例)。每个节点上会有多个 shard &#xff08;分片&#xff09;&#xff0c; P1 P2 是主分片, R1 R2…

达梦数据库——记录一次离谱的登录失败报错

好久没更新了哇 前面有整理过一些常见的数据库登录失败问题哈&#xff0c;今天记录一个遇到概率比较小&#xff0c;但碰上了一般不太容易找到原因的登录失败问题。 今天给客户同时初始化了三台服务器数据库&#xff0c;惟独这一台死活登不进去&#xff0c;满脑子问号&#xf…

【论文解读】Object Goal Navigation usingGoal-Oriented Semantic Exploration

论文&#xff1a;https://devendrachaplot.github.io/papers/semantic-exploration.pdf 代码&#xff1a;https://github.com/devendrachaplot/Object-Goal-Navigation 项目&#xff1a; Object Goal Navigation using Goal-Oriented Semantic Exploration example&#xff1…

代码随想录算法训练60 | 单调栈part03

84.柱状图中最大的矩形 代码随想录 今天是训练营最后一天&#xff0c;恭喜坚持两个月的录友们&#xff0c;接下来可以写一篇自己 代码随想录一刷的总结。好好回顾一下&#xff0c;这两个月自己的博客内容&#xff0c;以及自己的收获。

2、鼠标事件、键盘事件、浏览器事件、监听事件、冒泡事件、默认事件、属性操作

一、鼠标事件 1、单击事件&#xff1a;onclick <body><header id"head">我是头部标签</header> </body> <script> var head document.getElementById("head")head.onclick function () {console.log("我是鼠标单击…

金蝶云星空--写插件不重启IIS热更新简单配置指南

云星空7.5版本&#xff0c;以简单方式配置并测试了热更新的实现方式可行&#xff0c;操作如下&#xff08;7.5外版本没试过&#xff0c;大家可试下&#xff09;&#xff1a; 1、打开WebSite\App_Data\Common.config&#xff0c;修改appSettings&#xff0c;设置IsEnablePlugIn…

go slice 扩容实现

基于 Go 1.19。 go 的切片我们都知道可以自动地进行扩容&#xff0c;具体来说就是在切片的容量容纳不下新的元素的时候&#xff0c; 底层会帮我们为切片的底层数组分配更大的内存空间&#xff0c;然后把旧的切片的底层数组指针指向新的内存中&#xff1a; 目前网上一些关于扩容…