Springboot和easyExcel整合使用

2022-07-17 11:17:19

Springboot和easyExcel整合使用

EasyExcel是阿里巴巴开源的一个excel处理框架,以使用简单、节省内存著称。EasyExcel能大大减少占用内存的主要原因是在解析Excel时没有将文件数据一次性全部加载到内存中,而是从磁盘上一行行读取数据,逐个解析
EasyExcel采用一行一行的解析模式,并将一行的解析结果以观察者的模式通知处理(AnalysisEventListener)
使用springboot和easyExcel需要导入以下依赖

<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel --><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.1.1</version></dependency>

实体类中使用@ExcelProperty注解来表示excel标题行对应的属性

@DatapublicclassDictEeVo{@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;}

下面是easyExcel使用时导入数据所使用的方法,上传一个对应实体的Excel文件,通过继承AnalysisEventListener<T>类,泛型写导入所使用的实体类,重写其中的invoke方法来获取到一条一条的实体记录,通过mapper层插入到数据库中

/**
* 导入的方法
*/publicvoidimportDict(MultipartFile file){try{
            EasyExcel.read(file.getInputStream(), DictEeVo.class,newDictListener(baseMapper)).sheet().doRead();}catch(IOException e){
            e.printStackTrace();}}
/**
 * 导入监听器
 */publicclassDictListenerextendsAnalysisEventListener<DictEeVo>{private DictMapper dictMapper;/**
	* 通过构造器注入
	*/publicDictListener(DictMapper dictMapper){this.dictMapper= dictMapper;}@Overridepublicvoidinvoke(DictEeVo dictEeVo, AnalysisContext analysisContext){
        Dict dict=newDict();
        BeanUtils.copyProperties(dictEeVo,dict,Dict.class);
        dictMapper.insert(dict);}@OverridepublicvoiddoAfterAllAnalysed(AnalysisContext analysisContext){}}

导出方法如下,导出把记录导出到Excel文件中

publicvoidexportDict(HttpServletResponse response){try{
            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");

            List<Dict> dictList= baseMapper.selectList(null);
            List<DictEeVo> dictVoList=newArrayList<>(dictList.size());for(Dict dict: dictList){
                DictEeVo dictVo=newDictEeVo();
                BeanUtils.copyProperties(dict, dictVo, DictEeVo.class);
                dictVoList.add(dictVo);}

            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictVoList);}catch(IOException e){
            e.printStackTrace();}}
  • 作者:鹏举在努力
  • 原文链接:https://blog.csdn.net/weixin_43947145/article/details/117257345
    更新时间:2022-07-17 11:17:19