Springboot和easyExcel整合使用

Springboot和easyExcel整合使用

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


<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>easyexcelartifactId>
    <version>2.1.1version>
dependency>

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

@Data
public class DictEeVo {
     

	@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类,泛型写导入所使用的实体类,重写其中的invoke方法来获取到一条一条的实体记录,通过mapper层插入到数据库中

/**
* 导入的方法
*/
public void importDict(MultipartFile file) {
     
        try {
     
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
     
            e.printStackTrace();
        }
    }
/**
 * 导入监听器
 */
public class DictListener extends AnalysisEventListener<DictEeVo> {
     

    private DictMapper dictMapper;
	/**
	* 通过构造器注入
	*/
    public DictListener(DictMapper dictMapper) {
     
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(DictEeVo dictEeVo, AnalysisContext analysisContext) {
     
        Dict dict=new Dict();
        BeanUtils.copyProperties(dictEeVo,dict,Dict.class);
        dictMapper.insert(dict);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
     

    }
}

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

public void exportDict(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 = new ArrayList<>(dictList.size());
            for(Dict dict : dictList) {
     
                DictEeVo dictVo = new DictEeVo();
                BeanUtils.copyProperties(dict, dictVo, DictEeVo.class);
                dictVoList.add(dictVo);
            }

            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictVoList);
        } catch (IOException e) {
     
            e.printStackTrace();
        }

    }

你可能感兴趣的:(springboot,java,spring,boot,spring)