EasyExcel使用

一. EasyExcel简介

  1. 数据导入
  2. 数据导出: 统计信息归档
  3. 数据传输:异构系统之间数据传输

二. EasyExcel特点

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

三. EasyExcel使用

  1. 导入依赖

    <dependency>
            <groupId>com.alibabagroupId>
    		<artifactId>easyexcelartifactId>
    		<version>2.1.1version>
    	dependency>
    
  2. 创建实体类

    @Data
    public class Stu {
    
        //设置表头名称
        @ExcelProperty("学生编号")
        private int sno;
        
        //设置表头名称
        @ExcelProperty("学生姓名")
        private String sname;
    }
    
  3. 写入方法一

    public static void main(String[] args) throws Exception{
            String filename = "F:\\document\\excel_test.xlsx";
            EasyExcel.write(filename, Stu.class).sheet("写入方法一")
                    .doWrite(data());
        }
        private static List<Stu> data(){
            List<Stu> list = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                Stu data = new Stu();
                data.setSno(i);
                data.setSname("鸡你太美"+i);
                list.add(data);
            }
            return list;
        }
    
  4. 写入方法二

    public static void main(String[] args) {
            String filename = "F:\\document\\excel_test.xlsx";
            ExcelWriter excelWriter = EasyExcel.write(filename, Stu.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("写入方法二").build();
            excelWriter.write(data(),writeSheet);
            excelWriter.finish();
        }
    
  5. 读操作的监听器类

    public class ExcelListener extends AnalysisEventListener<Stu> {
        List<Stu> list = new ArrayList<>();
        @Override
        public void invoke(Stu user, AnalysisContext analysisContext) {
            System.out.println("User"+user);
            list.add(user);
        }
    
        @Override
        public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
            System.out.println("表头信息"+headMap);
        }
    
        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    
        }
    }
    
  6. 读取类

    public class ExcelRead {
        public static void main(String[] args) {
            String filename = "F:\\document\\excel_test.xlsx";
            EasyExcel.read(filename, Stu.class, new ExcelListener()).sheet().doRead();
    
        }
    }
    
  7. 写入多个工作表

     public static void main(String[] args) {
            String filename = "F:\\document\\excel_test2.xlsx";
            ExcelWriter excelWriter = EasyExcel.write(filename,Stu.class).build();
    
            WriteSheet writeSheet1 = EasyExcel.writerSheet(0,"学生一").head(Stu.class).build();
            WriteSheet writeSheet2 = EasyExcel.writerSheet(1,"学生二").head(Stu.class).build();
    
            excelWriter.write(data(),writeSheet1);
            excelWriter.write(data(),writeSheet2);
            excelWriter.finish();
        }
    

四. 字典导出功能

  1. 创建实体类,属性上加@ExcelProperty(value,index)

  2. service

    service extends ISerivce<Dict>{
        void exportData(HttpServletResponse response);
    }
    实现类
    @Override
        public void exportData(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);
                    dictVoList.add(dictVo);
                }
    
                EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictVoList);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    

五. 字典导入功能

  1. 创建监听器

    @Component
    public class DictListener extends AnalysisEventListener<DictEeVo> {
    
        @Autowired
        private DictMapper dictMapper;
    
        //一行一行读取
        @Override
        public void invoke(DictEeVo dictEeVo, AnalysisContext analysisContext) {
            //调用方法添加数据库
            Dict dict = new Dict();
            BeanUtils.copyProperties(dictEeVo,dict);
    
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<Dict>();
            queryWrapper.eq("id", dict.getId());
            Integer count = dictMapper.selectCount(queryWrapper);
    
            if(count>0){
                dictMapper.updateById(dict);
            }else{
                dictMapper.insert(dict);
            }
        }
        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    
        }
    }
    
    
  2. controller

    public R importData(MultipartFile file) {
        dictService.importDictData(file);
        return R.ok();
    }
    
    
  3. service

    @Autowired
    private DictListener dictListener;
    
    @Override
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,dictListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    

你可能感兴趣的:(java,jvm,开发语言)