EasyExcel导出列带约束
easyExcel导出列带约束
自定义拦截器.对第一列第一行和第二行的数据新增下拉框,显示 测试1 测试2
@Slf4j
public class CustomSheetWriteHandler implements SheetWriteHandler {
@Override
public void afterSheetCreate(SheetWriteHandlerContext context) {
log.info("第{}个Sheet写入成功。", context.getWriteSheetHolder().getSheetNo());
CellRangeAddressList cellRangeAddressList1 = new CellRangeAddressList(1, 65535, 2, 2);
DataValidationHelper helper1 = context.getWriteSheetHolder().getSheet().getDataValidationHelper();
DataValidationConstraint constraint1 = helper1.createExplicitListConstraint(new String[] {"测试1", "测试2"});
/* 指定行列约束 */
DataValidation dataValidation1 = helper1.createValidation(constraint1, cellRangeAddressList1);
// 阻止输入非下拉选项的值
dataValidation1.setErrorStyle(DataValidation.ErrorStyle.STOP);
dataValidation1.setShowErrorBox(true);
dataValidation1.setSuppressDropDownArrow(true);
dataValidation1.createErrorBox("提示", "此值与单元格定义格式不一致");
context.getWriteSheetHolder().getSheet().addValidationData(dataValidation1);
/* 冻结窗格 目前不生效 */
// writeSheetHolder.getSheet().createFreezePane(0, 1, 0, 1);
/* 默认筛选条件 */
context.getWriteSheetHolder().getSheet().setAutoFilter(CellRangeAddress.valueOf("1:1"));
}
}
注册拦截器
/**
* 自定义拦截器(上面几点都不符合但是要对单元格进行操作的参照这个)
* 1. 创建excel对应的实体对象 参照{@link DemoData}
* <p>
* 2. 注册拦截器 {@link CustomCellWriteHandler} {@link CustomSheetWriteHandler}
* <p>
* 2. 直接写即可
*/
@Test
public void customHandlerWrite() {
String fileName = TestFileUtil.getPath() + "customHandlerWrite" + System.currentTimeMillis() + ".xlsx";
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
EasyExcel.write(fileName, DemoData.class).registerWriteHandler(new CustomSheetWriteHandler())
.registerWriteHandler(new CustomCellWriteHandler())
.sheet("模板").doWrite(data());
}
/**
最终效果
License:
CC BY 4.0