最近测试测试时,提了一个需求,导入模板头部的必填项需要标红;因为我用的动态导出模板,不像之前公司那样,直接定义好一个excel模板,然后提供下载,那样直接修改excel模板就可以了。但是动态模板需要在导出时设置下头部样式实现。再经历了各种尝试后,本文坐下记录。 如果需要导入导出功能的,请参考前面的一篇《Easy Excel实现Excel的导入导出》。
策略类中的属性可以根据需求自己定义,我这里定了头部必填需要的几个属性。
/** * 单元自定义样式 * * @author gourd.hu */ @Slf4j public class CustomCellStyleStrategy extends AbstractCellStyleStrategy { /** * 操作行 */ private List<Integer> columnIndexes; /** * 操作列 */ private List<Integer> rowIndexes; /** * 颜色 */ private Short colorIndex; public CustomCellStyleStrategy(List<Integer> rowIndexes, List<Integer> columnIndexes, Short colorIndex) { this.rowIndexes = rowIndexes; this.columnIndexes = columnIndexes; this.colorIndex = colorIndex; } @Override protected void initCellStyle(Workbook workbook) { } /** * 自定义头部样式 * * @param cell * @param head * @param integer */ @Override protected void setHeadCellStyle(Cell cell, Head head, Integer integer) { // 获取workbook Workbook workbook = cell.getSheet().getWorkbook(); // 获取样式实例 WriteCellStyle headWriteCellStyle = new WriteCellStyle(); // 获取字体实例 WriteFont headWriteFont = new WriteFont(); // 设置字体样式 headWriteFont.setFontName("宋体"); // 设置字体大小 headWriteFont.setFontHeightInPoints((short)14); // 边框 headWriteFont.setBold(true); // 设置背景颜色为灰色 headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); if (CollectionUtils.isNotEmpty(columnIndexes) && columnIndexes.contains(cell.getColumnIndex()) && CollectionUtils.isNotEmpty(rowIndexes) && rowIndexes.contains(cell.getRowIndex()) && colorIndex != null) { // 设置指定单元格字体自定义颜色 headWriteFont.setColor(colorIndex); } headWriteCellStyle.setWriteFont(headWriteFont); // 获取样式实例 CellStyle cellStyle = StyleUtil.buildHeadCellStyle(workbook, headWriteCellStyle); // 单元格设置样式 cell.setCellStyle(cellStyle); } /** * 自定义内容样式 * * @param cell * @param head * @param integer */ @Override protected void setContentCellStyle(Cell cell, Head head, Integer integer) { } }工具类方法
/** * 导出文件 * 导出模板时,tList传一个空list即可 * @param tList 数据集 * @param tClass 数据类型 * @param <T> * @throws IOException */ public static <T> void writeSingleExcel(String fileName, String sheetName, List<T> tList, Class tClass, CustomCellStyleStrategy customCellStyleStrategy) throws IOException{ HttpServletResponse response = RequestHolder.getResponse(); try (ServletOutputStream outputStream = response.getOutputStream()){ setResponse(fileName, response); EasyExcel.write(outputStream, tClass).autoCloseStream(Boolean.TRUE) .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) .registerWriteHandler(new CustomCellWriteHandler()) .registerWriteHandler(customCellStyleStrategy) .sheet(sheetName) .doWrite(tList); } catch (Exception e) { errorWrite(response, e); } }代码均已上传至本人的开源项目 cloud-plus:https://blog.csdn.net/HXNLYW/article/details/104635673