模板渲染工具类
public class ExcelUtils {
/**
* 模板表头样式
* @param templateName "classpath:template/" 模板文件名称
* @param data 数据
* @param writeHandler 自定额填充策略
*/
public static String commonImport(String templateName, Object data, WriteHandler writeHandler) throws IOException {
Resource resource = new DefaultResourceLoader().getResource("classpath:template/" + templateName);
//输出文件
String fileName = System.getProperty("java.io.tmpdir")+ File.separator+"temp_"+System.currentTimeMillis() + ".xlsx";
try (ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(resource.getInputStream()).registerWriteHandler(writeHandler).build()) {
WriteSheet writeSheet = EasyExcel.writerSheet().build();
//开启excel 函数公式
Workbook workbook = excelWriter.writeContext().writeWorkbookHolder().getWorkbook();
workbook.setForceFormulaRecalculation(true);
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
excelWriter.fill(data, fillConfig, writeSheet);
excelWriter.finish();
}
return fileName;
}
}
失败行标红工具类
/**
* 单元格标红处理器
*/
@Slf4j
public class CustomerCellHandler implements CellWriteHandler {
public CustomerCellHandler(List<Integer> failRowIndex) {
this.failRowIndex = failRowIndex;
}
/**
* 失败行下标数组
*/
private final List<Integer> failRowIndex;
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
// 当前事件会在 数据设置到poi的cell里面才会回调
// 判断不是头的情况 如果是fill 的情况 这里会==null 所以用not true
if (!context.getHead()) {
// 第一个单元格
// 只要不是头 一定会有数据 当然fill的情况 可能要context.getCellDataList() ,这个需要看模板,因为一个单元格会有多个 WriteCellData
WriteCellData<?> cellData = context.getFirstCellData();
Integer rowNum = context.getRow().getRowNum();
if (failRowIndex.contains(rowNum)) {
WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
WriteFont writerFont = new WriteFont();
writerFont.setColor(IndexedColors.RED.getIndex());
writeCellStyle.setWriteFont(writerFont);
}
}
}
}
标签:failRowIndex,EasyExcel,导入,标红,context,excelWriter,public,模板 From: https://www.cnblogs.com/cxyfyf/p/17434029.html