一. 概述
本文将用示例介绍如何用EasyExcel导出下拉框
二. 示例
2.1 编写样式处理类: TitleHandler
@Slf4j
public class TitleHandler implements SheetWriteHandler {
/**
* 下拉框值
*/
private Map<Integer,String[]> dropDownMap;
/**
* 多少行有下拉
*/
private final static Integer rowSize = 200;
public TitleHandler(Map<Integer,String[]> dropDownMap) {
this.dropDownMap = dropDownMap;
}
@Override
public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
}
@Override
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
Sheet sheet = writeSheetHolder.getSheet();
DataValidationHelper helper = sheet.getDataValidationHelper();
dropDownMap.forEach((celIndex, strings) -> {
// 区间设置
CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(1, rowSize, celIndex, celIndex);
// 下拉内容
DataValidationConstraint constraint = helper.createExplicitListConstraint(strings);
DataValidation dataValidation = helper.createValidation(constraint, cellRangeAddressList);
sheet.addValidationData(dataValidation);
});
}
}
2.2 编写工具类:
public class EasyExcelUtil {
public static <T> void writeExcelWithModel(OutputStream outputStream, Class<T> clazz, Map<Integer,String[]> dropDownMap) throws IOException {
EasyExcel.write(outputStream, clazz).registerWriteHandler(new TitleHandler(dropDownMap)).sheet("模板").doWrite(ListUtil.empty());
}
}
2.3 测试
@Override
public void importTemplate(HttpServletResponse response, String departId) throws IOException {
// 输出流
OutputStream os = response.getOutputStream();
HashMap<Integer, String[]> dropDownMap = new HashMap<>();
// 指定下拉框
String[] deptName= entDepartmentMapper.selectDeptName(departId);
dropDownMap.put(5,deptName);//部门
String[] type = {"全部员工类型","在职员工","退休员工"};
dropDownMap.put(3,type);
EasyExcelUtil.writeExcelWithModel(os, EntStaffVo.class, dropDownMap);
}