/**
* 自定义拦截器.填充下拉选项 key 就是 第几列(从0开始),value 就是这一列 你的下拉数据
*
*/
@Slf4j
@AllArgsConstructor
public class CustomSheetOptionWriteHandler implements SheetWriteHandler {
/**
* 每组下拉选 数据
*/
private Map<Integer, List<String>> optionGroupMap;
@Override
public void afterSheetCreate(SheetWriteHandlerContext context) {
log.info("第{}个Sheet写入成功。", context.getWriteSheetHolder().getSheetNo());
//获取下拉数据
Optional.ofNullable(optionGroupMap).orElse(new HashMap<>()).forEach((columnIndex, options) -> {
// 区间设置 第一列第一行和第二行的数据。由于第一行是头,所以第一、二行的数据实际上是第二三行
CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(1, 65535, columnIndex, columnIndex);
DataValidationHelper helper = context.getWriteSheetHolder().getSheet().getDataValidationHelper();
DataValidationConstraint constraint = helper.createExplicitListConstraint(options.toArray(new String[0]));
DataValidation dataValidation = helper.createValidation(constraint, cellRangeAddressList);
context.getWriteSheetHolder().getSheet().addValidationData(dataValidation);
});
}
}
先创建这个处理器 去填充下拉数据,再使用文章来源:https://uudwc.com/A/oraWz
@GetMapping("download")
public void download(HttpServletResponse response) throws IOException {
try {
ClassPathResource cpr = new ClassPathResource("123.xlsx");
// 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("123", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
//mock数据
Map<Integer, List<String>> data = getOptionGroupList();
EasyExcel.write(response.getOutputStream())
.withTemplate(cpr.getInputStream()).
registerWriteHandler(new CustomSheetOptionWriteHandler(data))
.sheet(0)
.doWrite(new ArrayList<>());
} catch (Exception e) {
e.printStackTrace();
}
}
private Map<Integer, List<String>> getOptionGroupList() {
Map<Integer, List<String>> data = new HashMap<>();
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue;
}
data.put(i, Arrays.asList("列" + i + "选项a", "列" + i + "选项b", "列" + i + "选项c"));
}
return data;
}
文章来源地址https://uudwc.com/A/oraWz