EasyExcel是阿里巴巴对POI封装的一个库,号称解决了POI的OOM问题,并且在使用上也更方便一些Github:[](https://github.com/alibaba/ea...
然而我在使用的时候发现还是有很多坑,其中一个比较头疼的是对单个单元格样式的设置。EasyExcel提供了一个BaseRowModel作为每行数据的一个模型,并且其中有一个属性cellStyleMap
代表每列样式的集合,本来我以为这个只要在自己定义模型的时候,也把CellStyle
定义进去就行了,然而,还是我想多了……定义了CellStyle
并没有什么卵用,这是第一个蛋疼的地方
/**
* Excel基础模型
* @author jipengfei
*/
public class BaseRowModel {
/**
* 每列样式
*/
private Map<Integer,CellStyle> cellStyleMap = new HashMap<Integer,CellStyle>();
public void addStyle(Integer row, CellStyle cellStyle){
cellStyleMap.put(row,cellStyle);
}
public CellStyle getStyle(Integer row){
return cellStyleMap.get(row);
}
public Map<Integer, CellStyle> getCellStyleMap() {
return cellStyleMap;
}
public void setCellStyleMap(Map<Integer, CellStyle> cellStyleMap) {
this.cellStyleMap = cellStyleMap;
}
}
后来测试半天,才发现创建CellStyle
时必须通过一个Workbook
对象来创建,而这个Workbook
不能随便新建一个对象完事儿,得用你当前写入的Workbook
来创建对应的CellStyle
样式才能起作用。然而……事情并没有那么简单,经过我对源码的反复查看,EasyExcel
生成excel表的步骤是用一个ExcelWriter
来写入数据,并没有提供获取Workbook的方法,不知道什么原因让阿里巴巴不提供这样一个接口……这是第二个蛋疼的地方
既然没有提供接口,那就只能用反射来硬刚了,下面就直接上代码了
我这里是在开始写数据之前就将每张表的CellStyle
与每张表关联起来,再在后面的handler中获取到这个CellStyle
进行设置
package edu.uddp.util;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.contex