如题 :
公司有个需求 是导入的要每个字段进行校验,不符合规则则不让导入并保存进行导出并将错误字段进行标红
公司用的是EasyExcel做的导出 网上查询相关资料 找到解决办法如下
了解到EasyExcel可以进行自定义样式
以下为代码
EasyExcel.write(response.getOutputStream(), TServicePersonExcelNewDTO.class)
.inMemory(true)
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())//自定义样式
.registerWriteHandler(new CustomCellWriteHandler())//自定义样式
.sheet().doWrite(list);
以下为自定义样式类 因我需求是单元格变色 所以字体变色就进行注释处理了 可以根据自己需求进行自己选择
public class CustomCellWriteHandler extends AbstractCellWriteHandler {
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
// 设置行高
short height = 650;
row.setHeight(height);
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
Sheet sheet = writeSheetHolder.getSheet();
sheet.setColumnWidth(cell.getColumnIndex(), 3000);
//当前行的第i列
int i = cell.getColumnIndex();
//不处理第一行
if (0 != cell.getRowIndex()) {
//此处判断为不符合要求 所以需求进行标红处理 可以根据自己需求进行判断使用 或者全量使用
if (cell.getStringCellValue().contains("_false")) {
// 根据单元格获取workbook
Workbook workbook = cell.getSheet().getWorkbook();
//设置行高
writeSheetHolder.getSheet().getRow(cell.getRowIndex()).setHeight((short) (1.4 * 256));
// 单元格策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
// 设置背景颜色白色
contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
// 设置垂直居中为居中对齐
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 设置左右对齐为靠左对齐
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
// 设置单元格上下左右边框为细边框
contentWriteCellStyle.setBorderBottom(BorderStyle.MEDIUM);
contentWriteCellStyle.setBorderLeft(BorderStyle.MEDIUM);
contentWriteCellStyle.setBorderRight(BorderStyle.MEDIUM);
contentWriteCellStyle.setBorderTop(BorderStyle.MEDIUM);
// 创建字体实例
WriteFont cellWriteFont = new WriteFont();
// 设置字体大小
//cellWriteFont.setFontName("宋体");
cellWriteFont.setFontHeightInPoints((short) 12);
//设置字体颜色
//cellWriteFont.setColor(IndexedColors.RED1.getIndex());
//单元格颜色
contentWriteCellStyle.setFillForegroundColor(IndexedColors.RED1.getIndex());
contentWriteCellStyle.setWriteFont(cellWriteFont);
CellStyle cellStyle = StyleUtil.buildHeadCellStyle(workbook, contentWriteCellStyle);
//设置当前行第i列的样式
cell.getRow().getCell(i).setCellStyle(cellStyle);
} }
}
以下为导出效果 可以看到不符合要求部分背景色已变成红色