easyexcel 实现导入导出

发布时间 2023-12-11 22:22:02作者: 朱呀朱~

easyExcel 导入导出

导入

  • 官方文档:https://easyexcel.opensource.alibaba.com/docs/current/

    • 使用文档中的依赖配置
  • vue 前端使用 <el-upload> 组件:

    <el-upload
               class="upload-demo"
               :auto-upload="false"
               :show-file-list="false"
               :on-change="importExcel">
        <el-button type="primary" :icon="Upload" >商品导入</el-button>
    </el-upload>
    
    • 方法事件:

      /**
       * 导入商品
       */
      const importExcel = (uploadFile) => { 
          const fileName = uploadFile.name;
          const judge = fileName.substring(fileName.length - 4);
          if (!(judge === 'xlsx' || judge === '.xls')) {
              alert('只能上传Excel文件!');
          } else{
              goodsExcelApi.importExcel(uploadFile.raw, function (res) { // log查看可知,文件就存在xxx.raw里
                  if (res.meta && res.meta.success) {
                      ElMessage({
                          type: 'success',
                          message: '成功完成导入操作'
                      })
                      importData.value = res.data;
                  }
              })
          }
      }
      
  • api 读方法(前端路由想发文件到后端,就要用 formData 封装)

    /**
     * 导入商品
     */
    importExcel(file, successCallBack) {
        const formData = new FormData();
        formData.append('file', file);
        const url = goodsExcelService + "/importExcel";
        axiosUtil.post(url, formData,function (res) {
            if (typeof successCallBack == "function") {
                successCallBack(res);
            }
        },function(error) {
            if (typeof errorCallBack == "function") {
                errorCallBack(error);
            } else {
                throw new Error(error);
            }
        })
    }
    
  • 后端接收

    @PostMapping(value="/importExcel")
    @ResponseBody
    public String importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        ExcelListenerUtil excelListenerUtil = new ExcelListenerUtil(goodsExcelService);
    
        /**
             * 参数1 可以是 文件对象 文件路径 文件流
             * 参数2 读取的数据 封到哪个类的对象中
             * 参数3 监听器 每读取一行 会调用 监听器的 invoke 方法
             */
    
        ExcelReaderBuilder read = EasyExcel.read(file.getInputStream(), GoodsExcel.class, excelListenerUtil);
        ExcelReaderSheetBuilder sheet = read.sheet();
        sheet.doRead(); // 读取sheet
        
        ExcelListenerUtil.自定义方法处理接收的所有数据;
        // 将获取的数据保存到数据库中
            
        System.out.println("文件导入操作完成");
        return "success";
    }
    
  • 监听器(extends AnalysisEventListener 后就只需要重写两个方法:invokedoAfterAllAnalysed

    @Slf4j
    public class ExcelListenerUtil extends AnalysisEventListener<GoodsExcel> {
    
        private GoodsExcelService goodsExcelService;
    
        public ExcelListenerUtil(GoodsExcelService goodsExcelService) {
            this.goodsExcelService = goodsExcelService;
        }
    
        /**
         * 存储所有读取的数据
         */
        private List<GoodsExcel> goodsExcelList = new ArrayList<>();
        /**
         * 包装好的数据(这里是指返回给前端的数据,是自定义部分)
         */
        public GoodsExcelVO goodsExcelVO;
    
        @Override
        public void invoke(GoodsExcel goodsExcel, AnalysisContext analysisContext) {
    //        每读取一行数据都会调用此方法
            goodsExcelList.add(goodsExcel);
        }
    
        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            // 从excel中读取了所有的信息最后的操作
        }
    
        public 自己根据需求编写 自定义方法处理接收的所有数据() {
    
            for (GoodsExcel g: goodsExcelList) { // 循环每一条数据
    
                Set<ConstraintViolation<GoodsExcel>> violations  =  ValidationUtil.getValidator().validate(g);
                if(violations.size()>0){ // 这里是最普通的实体类注解的校验
                    // 校验不通过的操作
                    continue;
                }
                // ...... 进行数据的校验
                
                // 通过校验
                // ......操作
            }
            // 最后操作
            return 自己根据需求编写;
        }
    }
    
    

导出

  • 前端就只有一个导出的按钮触发事件方法

  • 后端操作:

    /**
     * 导出全部商品
     */
    public String exportExcel(HttpServletResponse response) {
        try {
            List<GoodsExcel> goodsList = goodsExcelService.exportGoods(); // 获取数据库中要导出的信息
            List<GoodsExcel> newData = changeGoodsExcel(goodsList); // 处理数据库中的信息,是显示在excel中的数据,比如化code为name
    
            EasyExcel.write(response.getOutputStream(), GoodsExcel.class).autoCloseStream(Boolean.FALSE).sheet("商品") // 导出,根据网页形式的
                .doWrite(newData);
            return "success";
        } catch (Exception e) {
            return "fail";
        }
    }