导入EasyExcel的依赖包
<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.6</version>
</dependency>
编写一个简单的实体类
@ExcelProperty(value = "id",index = 0)
private Long id;
@ExcelProperty(value = "上级id",index = 1)
private Long parentId;
@ExcelProperty(value = "名称",index = 2)
private String name;
@ExcelProperty(value = "值",index = 3)
private String value;
@ExcelProperty(value = "编码",index = 4)
private String dictCode;
@ExcelProperty(value = "id",index = 0)
value:在表格中头部的名称
index:表示是第几个单元格
导出Excel前 需要设置请求头的信息
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
//这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("数据字典", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
省略相关业务操作 导出代码如下
EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictVoList);
导入不用设置请求头信息 但是要单独配置一个监听器
public class ExcelListener extends AnalysisEventListener<UserData> {
#通过构造器传入对应Mapper用于数据库操作
private DictMapper dictMapper;
public DictListener(DictMapper dictMapper) {
this.dictMapper = dictMapper;
}
//一行一行读取 从第二行开始读取
@Override
public void invoke(UserData userData, AnalysisContext analysisContext) {
System.out.println(userData);
}
//读取头部信息
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
System.out.println(headMap.toString());
}
//读取之后执行
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
}
还是省略一些业务代码 直接甩导入相关代码
//写入 | 导入
EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
以上就是boot集成EasyExcel 的使用