easyPoi实现excel导入导出
贴出easyPoi教程网址 点这
为什么使用easypoi?
最近业务里频繁的导入导出Excel表格,需求很大,一开始本人使用的是Apache的POI,感觉还是比较复杂的,相对于easyPOI来说。看到这个名字就很容易想到简单易用,他们的出发点就是为了不让我们重复造轮子,简单的直接加上模板,轻松实现导出模板。忙里抽闲总结一下,省的用过之后就忘记了。
引入easypoi的相关依赖
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.2.0</version>
</dependency>
使用模板导出,使用的最为广泛
@Test
public void contextLoads() {
TemplateExportParams templateExportParams = new TemplateExportParams("C:\\Users\\HP\\Desktop\\模板.xlsx");
Map<String, Object> map = new HashMap<>();
map.put("provinceName", "XX省");
map.put("cityName", "XX市");
map.put("areaName", "XX区");
map.put("schoolName", "XX中学");
map.put("grade", "初一");
map.put("nowDate", "2018-12-25");
map.put("mmp", "");
List<Map<String, String>> mapList = new ArrayList<>();
for (int i = 0; i < 4; i++) {
Map<String, String> ml = new HashMap<>();
ml.put("id", "1");
ml.put("className", "一班");
ml.put("studentName", "老王");
ml.put("code", "10000011");
ml.put("odVision", "4.8");
ml.put("osVision", "5.3");
ml.put("odSph", "+0.3");
ml.put("odCyl", "+0.3");
ml.put("odAxial", "0.0");
ml.put("osSph", "+0.5");
ml.put("osCyl", "+0.3");
ml.put("osAxial", "-0.2");
ml.put("odSeriesMirror", "5");
ml.put("osSeriesMirror", "4");
ml.put("odAmetropia", "3");
ml.put("osAmetropia", "2");
mapList.add(ml);
}
map.put("maplist", mapList);
Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams, map);
File saveFile = new File("F:/tmp/");
if (!saveFile.exists()) {
saveFile.mkdir();
}
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream("F:/tmp/视力报告.xlsx");
workbook.write(fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
模板的写法。
运行之:
是不是超级简单。
导入
@PostMapping("/scheduleImport")
public Object scheduleImport(@RequestParam("file") MultipartFile file) {
ImportParams params = new ImportParams();
params.setHeadRows(1); //有几行头
params.setKeyIndex(3); //第几列cell为空时,认为该行为无效数据
List<ExcelImportVo> excelImportList = ExcelImportUtil.importExcel(file.getInputStream(), ExcelImportVo.class, params);
return "";
}
注解Excel与文件中的表头一一对应即可。
四行代码搞定读取Excel,剩下的就是自己的业务了。这是最简单是使用,里边还有很强大的注解形式,api也很丰富,大家可以去尝试一下,再也不要造轮子了,好爽。