一、2.x版本和3.0.5版本的头样式
本人在开发中用到Easyexcel的第三方jar包,遇到需要单独设置表头单元格每一格的样式的情况。
1.官方文档给出的 HorizontalCellStyleStrategy只能实现把整个表头的样式都设置为一样的。
2.而注解方式并不适合动态导出表头的需要,除非进行反射生成JavaBean,但实现起来过于繁琐。
于是在网上搜索相关的博客发现均采用了StyleUtils的buildlHeadCellStyle方法,该方法在3版本中已去除,笔者在StyleUtil中看到原来的方法似乎合并了表头和表内容的Style方法,改为了buildCellStyle(),但是在把该方法改为buildCellStyle()方法后重新设置并没有成功获取到表头的样式。
// 新建WriteCellStyle
WriteCellStyle writeCellStyle=new WriteCellStyle();
// 设置自定义的表头样式
writeCellStyle.setFillForegroundColor(complexHeadStyle.getIndexColor());
// 获取样式实例 该方法已在3.x后去除
CellStyle cellStyle = StyleUtil.buildHeadCellStyle(workbook, headWriteCellStyle);
// 单元格设置样式
cell.setCellStyle(cellStyle);
仔细查阅官方文档,并没有给出不用注解的单独设置表头样式的方法,但是在=注释中有一句可以看出一点端倪。
// HorizontalCellStyleStrategy 每一行的样式都一样 或者隔行一样
// AbstractVerticalCellStyleStrategy 每一列的样式都一样 需要自己回调每一页
二、源码
寻找官方demo中的AbstractCellStyleStrategy实现类中发现这样的一个抽象子类AbstractVerticalCellStyleStrategy,该类是上面官方文档注释提到的列样式实现的一种策略,查看后该类里有两个方法,猜想能否直接复写这两个方法能否直接设置头样式。
@Override
protected void setHeadCellStyle(CellWriteHandlerContext context) {
if (stopProcessing(context)) {
return;
}
WriteCellData<?> cellData = context.getFirstCellData();
WriteCellStyle.merge(headCellStyle(context), cellData.getOrCreateStyle());
}
protected WriteCellStyle headCellStyle(CellWriteHandlerContext context) {
return this.headCellStyle(context.getHeadData());
}
protected WriteCellStyle headCellStyle(Head head) {
return null;
}
设置样式代码
@Slf4j
public class CustomCellStyleStrategy extends AbstractVerticalCellStyleStrategy {
/**
* 操作列
*/
private List<Integer> columnIndexes;
public CustomCellStyleStrategy( List<Integer> columnIndexes ) {
this.columnIndexes = columnIndexes;
}
@Override
protected WriteCellStyle headCellStyle(Head head) {
// 获取样式实例
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
// 获取字体实例
WriteFont headWriteFont = new WriteFont();
// 设置字体样式
headWriteFont.setFontName("宋体");
// 设置字体大小
headWriteFont.setFontHeightInPoints((short)14);
// 边框
headWriteFont.setBold(true);
// 设置表头单元格必填时为红色
if (columnIndexes.contains(head.getColumnIndex())) {
headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
}
//非必填时为蓝色
else{
headWriteCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
}
headWriteCellStyle.setWriteFont(headWriteFont);
return headWriteCellStyle;
}
}
List<Integer> columnIndexes = Arrays.asList(0,3);
CustomCellStyleStrategy customCellStyleStrategy = new CustomCellStyleStrategy(columnIndexes);
//new ArrayList是数据列为空, 自定义样式注册在Writer上
EasyExcel.write(response.getOutputStream()).head(header).registerWriteHandler(customCellStyleStrategy).sheet("模板").doWrite(new ArrayList<>());
response.getOutputStream().close();
结果:成功实现自定义表头样式

1万+

被折叠的 条评论
为什么被折叠?



