项目场景:
最近做到一个业务需求是,要做一个物品管理页面的excel模板导出,导出的excel信息填充后做导入使用
问题描述:
这个关键是,模板是动态的,不同的物品有着不同的属性,相对应的excel 列数也是动态的;后面思索好长一段时间,才想到这么一个“半动态化”的导出功能:编写过程如下1. 导入jar包
<!--easypoi 导出-->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.1.0</version>
</dependency>
2. 实体类的生成:
这里用的是模板导出,实体类就不需要使用额外的注解了,按业务需求构建即可.
3. Controller层设计:
/**
* 查询物品模板
*(动态导出功能)
* @param orgCode
* @return
*/
@GetMapping("/office/goods/export")
public void export(String typeCode, String orgCode, String personCode, HttpServletResponse response) throws Exception {
//获取excel表对应属性名(列名)
OfficeTypeContentVo officeTypeContent = new OfficeTypeContentVo();
officeTypeContent.setTypeCode(typeCode);
List<OfficeTypeContentVo> list = officeTypeService.getTypeContent(officeTypeContent);
//数据整理(封装好的exportExcel函数 键值对的值要求是用集合接收)
Map<String, Object> data = new HashMap<>();
for (int i = 0; i < list.size(); i++) {
OfficeTypeContentVo vo = new OfficeTypeContentVo();
List<OfficeTypeContentVo> voList = new ArrayList<>();
vo.setColumnName(list.get(i).getColumnName());
voList.add(vo);
String name = "data"+i;
data.put(name,voList);
}
//引用模板
TemplateExportParams params = new TemplateExportParams("/templates/typeContent.xlsx", true);
params.setColForEach(true);
Workbook workbook = ExcelExportUtil.exportExcel(params, data);
//设置编码
response.setCharacterEncoding("UTF-8");
//设置响应头 直接下载
response.setContentType("application/x-download");
String filedisplay = "";
try {
//设置excel名字
filedisplay = URLEncoder.encode("物品信息表.xlsx", "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setHeader("content-disposition", "attachment;filename=" + filedisplay);
OutputStream out = null;
try {
out = response.getOutputStream();
workbook.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4. 模板设计:
这份模板 也是这次导出是 "半动态导出"的原因:需要我们提前设计给足 列数,才能自由导出
总结:
编码使用过程中碰到了 强转问题(前文提到需用集合接收的原因),以及文件路径找不到等问题,在百度检索下都找到了解决方法,后面如果想出可以改进的点还会不断改进的,后续的导入也会更新上来。加油!!!
java.lang.ClassCastException: com.hsit.mobileportal.entity.vo.OfficeTypeCont