easyexcel默认的表头样式实在是太丑了。。。
EasyExcel自定义单元格样式
前言
最近在业务中使用 easyexcel 来替代 poi 解析和创建 excel 文件,但与 poi
不同的是,easyexcel 的表头是有默认的样式的
image-20241209093147776
灰灰的我觉得特别丑,还不如 excel
默认的样式,于是我准备将单元格样式自定义
主要函数
1 2 3 4 public T registerWriteHandler (WriteHandler writeHandler) { if (((WriteBasicParameter)this .parameter()).getCustomWriteHandlerList() == null ) { ((WriteBasicParameter)this .parameter()).setCustomWriteHandlerList(new ArrayList ()); }
这是在创建 excel 文件时传入自定义写入策略的函数,通过链式调用调用
调用示例:
1 2 3 4 5 EasyExcel.write(file, DataItem.class) .registerWriteHandler(ExcelUtil.getHorizontalCellStyleStrategy()) .excludeColumnFiledNames(columnsToExclude) .sheet("Sheet1" ) .doWrite(dataItemList);
自定义工具类
在这个函数我们需要传一个参数
CellStyle,这里我们通过自定义工具类来自定义单元格格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 public static HorizontalCellStyleStrategy getHorizontalCellStyleStrategy () { WriteCellStyle headWriteCellStyle = new WriteCellStyle (); headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.index); headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER); headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); headWriteCellStyle.setBorderBottom(BorderStyle.NONE); headWriteCellStyle.setBorderLeft(BorderStyle.NONE); headWriteCellStyle.setBorderRight(BorderStyle.NONE); headWriteCellStyle.setBorderTop(BorderStyle.NONE); headWriteCellStyle.setWrapped(true ); WriteFont headWriteFont = new WriteFont (); headWriteFont.setBold(false ); headWriteFont.setFontName("宋体" ); headWriteFont.setFontHeightInPoints((short )11 ); headWriteCellStyle.setWriteFont(headWriteFont); WriteCellStyle contentWriteCellStyle = new WriteCellStyle (); contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND); contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex()); contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER); contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); contentWriteCellStyle.setBorderBottom(BorderStyle.NONE); contentWriteCellStyle.setBorderLeft(BorderStyle.NONE); contentWriteCellStyle.setBorderRight(BorderStyle.NONE); contentWriteCellStyle.setBorderTop(BorderStyle.NONE); contentWriteCellStyle.setWrapped(true ); WriteFont contentWriteFont = new WriteFont (); contentWriteFont.setFontHeightInPoints((short )11 ); contentWriteFont.setFontName("宋体" ); contentWriteCellStyle.setWriteFont(contentWriteFont); return new HorizontalCellStyleStrategy (headWriteCellStyle, contentWriteCellStyle); }
导出效果
导出效果
这样就正常多了