Java实现下载excel模板,并实现自定义下拉框
@GetMapping("excel/download")
@ApiOperation(value = "模板下载")
public void getUserRecordTemplate(HttpServletResponse response, HttpServletRequest request) throws IOException {
OutputStream outputStream = response.getOutputStream();
InputStream inputStream = new ClassPathResource("example/excel/download_template_user_record.xlsx").getInputStream();
try {
String fileName = "导入模板";
String fileName3 = URLEncoder.encode(fileName, "utf-8");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''"+fileName3+".xlsx");
response.setContentType("application/msexcel");// 定义输出类型
response.setCharacterEncoding("UTF-8");
//获取该类声明的所有字段
Field[] fields = UserRecordExcelExportResult.class.getDeclaredFields();
//响应字段对应的下拉集合
Map<Integer, String[]> map = new HashMap<>();
Field field = null;
//从数据库里获取下拉框选项
List<XcUserLevel> list = xcUserLevelService.list();
// List<SysDept> list1 = sysDeptService.list();
List<String> collect = list.stream().map(XcUserLevel::getName).collect(Collectors.toList());
// List<String> collect1 = list1.stream().map(SysDept::getName).collect(Collectors.toList());
//找到需要对应的下拉框位置
// map.put(11,collect1.toArray(new String[0]));
map.put(12,collect.toArray(new String[0]));
// 循环判断哪些字段有下拉数据集,并获取
/*for (int i = 0; i < fields.length; i++) {
field = fields[i];
// 解析注解信息
DropDownSetField dropDownSetField = field.getAnnotation(DropDownSetField.class);
if (null != dropDownSetField) {
//调用下拉框数据源的方法
String[] source = ResoveDropAnnotationUtil.dynamicListResove2(dropDownSetField, field.getName(),staffId);
if (null != source && source.length > 0) {
map.put(i, source);
}
}
}*/
ExcelWriter excelWriter = EasyExcel.write(outputStream)
//将保存下拉框的map放入excelWriter
.registerWriteHandler(new CustomSheetWriteHandler(map))
.withTemplate(inputStream)
.build();
WriteSheet writeSheet = EasyExcel.writerSheet(0,"Sheet1").build();
excelWriter.write(new ArrayList<>(), writeSheet);
excelWriter.finish();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
从resoues包里获取excel文件