elment UI + EasyExcel 实现 导入

打印 上一主题 下一主题

主题 643|帖子 643|积分 1929

前端组件
  1. <hd-flex>
  2.                 <el-dialog v-model="isUploadDialog" width="50%" lock-scroll=false>
  3.                     <el-upload
  4.                             class="upload-demo"
  5.                             drag
  6.                             :action="url"
  7.                             :on-success="success"
  8.                             :on-error="error"
  9.                             :headers="uploadHeaders"
  10.                             :limit="1"
  11.                             :on-exceed="handleExceed"
  12.                             :file-list="fileList"
  13.                             accept=".xlsx,.xls">
  14.                         <i class="el-icon-upload"></i>
  15.                         <em>点击上传</em>
  16.                         只能上传xlsx/xls文件,且不超过500kb
  17.                     </el-upload>
  18.                 </el-dialog>
  19.             </hd-flex><br><br>//变量
复制代码
  1. url: `${conf.BASE_URL}/core/ssqd/importS`,<br>isUploadDialog: false,<br>fileList: [],<br><br><br>// 方法
复制代码
  1. //导入<br>async importS() {<br>    this.fileList=[];<br>    this.isUploadDialog=true;<br>},<br>success(response, file, fileList){<br>    if(response.code=='500'){<br>        this.$hd.message.error(response.errorBody.errorMessage);<br>    }<br>    if(response.code=='200'){<br>        this.$hd.message.ok('导入成功!');<br>        this.isUploadDialog=false;<br>        this.$refs.table.onSearch();<br>    }<br><br><br>},<br>error(err, file, fileList){<br>    this.$hd.message.error(err);<br><br>},<br>handleRemove(file, fileList) {<br>    console.log(file, fileList)<br>},<br>handlePreview(file) {<br>    console.log(file)<br>},<br>handleExceed(files, fileList) {<br>    this.$message.warning(<br>        `当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${<br>            files.length + fileList.length<br>        } 个文件`<br>    )<br>},<br>beforeRemove(file, fileList) {<br>    return this.$confirm(`确定移除 ${file.name}?`)<br>},
复制代码
Java  
  1. Controller
复制代码
  1.         @ApiOperation("上传")
  2.         @ApiImplicitParams({
  3.                         @ApiImplicitParam(name = "file",value = "文件",dataTypeClass = MultipartFile.class,required = true,paramType = "")
  4.         })
  5.         @PostMapping ("/importS")
  6.         public RestResponse<String> uploadExcel(MultipartFile file)throws IOException {
  7.                 String HZ = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
  8.                 if(".xlsx.xls".indexOf(HZ) < 0){
  9.                         throw new BaseException("500","导入的文件类型不正确,只能导入Excel文件");
  10.                 }
  11.                 EasyExcel.read(file.getInputStream(), SsqdVO.class,new UploadListenerBySsqd(iSsqdService)).sheet() .doRead();;
  12.                 return new RestResponse<> ("ok");
  13.         } 
复制代码
javaBean
  1. package com.hopedove.coreserver.vo.sygl;
  2. import com.alibaba.excel.annotation.ExcelProperty;
  3. import com.baomidou.mybatisplus.annotation.TableField;
  4. import com.baomidou.mybatisplus.annotation.TableId;
  5. import com.baomidou.mybatisplus.annotation.TableName;
  6. import java.io.Serializable;
  7. import java.math.BigDecimal;
  8. import java.util.Date;
  9. import com.hopedove.commons.vo.BaseModel;
  10. import lombok.Data;
  11. /**
  12. * 璇曠罕娓呭崟
  13. * @TableName T_JS_SYGL_SSQD
  14. */
  15. @TableName(value ="T_JS_SYGL_SSQD")
  16. @Data
  17. public class SsqdVO  extends BaseModel implements Serializable {
  18.     /**
  19.      * 璇曠罕娓呭崟ID
  20.      */
  21.     @TableId
  22.     private String SSQDID;
  23.     /**
  24.      * 坯布类型
  25.      */
  26.     @ExcelProperty(value ="试纱类型", index = 0)
  27.     private String PBLX;
  28.     /**
  29.      * 布号
  30.      */
  31.     @ExcelProperty(value ="布号", index = 1)
  32.     private String BH;
  33.     /**
  34.      * 支数
  35.      */
  36.     @ExcelProperty(value ="支数", index = 2)
  37.     private String ZS;
  38.     /**
  39.      * 产地
  40.      */
  41.     @ExcelProperty(value ="产地", index = 3)
  42.     private String CD;
  43.     /**
  44.      * 批号
  45.      */
  46.     @ExcelProperty(value ="批号", index = 4)
  47.     private String PH;
  48.     /**
  49.      * 重量
  50.      */
  51.     @ExcelProperty(value ="重量", index = 5)
  52.     private BigDecimal ZL;
  53.     /**
  54.      * 备注
  55.      */
  56.     @ExcelProperty(value ="备注", index = 6)
  57.     private String REMARK;
  58.     @TableField(exist = false)
  59.     private String GY;
  60. }
复制代码
  监听器: 判断上传表格是否符合要求
  1. package com.hopedove.coreserver.service.impl.sygl;
  2. import com.alibaba.excel.context.AnalysisContext;
  3. import com.alibaba.excel.event.AnalysisEventListener;
  4. import com.alibaba.nacos.common.utils.CollectionUtils;
  5. import com.hedu.sweet.starter.utils.exception.BusinException;
  6. import com.hopedove.coreserver.service.sygl.ISsqdService;
  7. import com.hopedove.coreserver.vo.sygl.SsqdVO;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. import java.util.Map;
  11. public class UploadListenerBySsqd extends AnalysisEventListener<SsqdVO>  {
  12.     private ISsqdService iSsqdService;
  13.     public UploadListenerBySsqd(ISsqdService iSsqdService) {
  14.         this.iSsqdService = iSsqdService;
  15.     }
  16.     private List<SsqdVO> list = new ArrayList<>(100);
  17.     @Override
  18.     public void invoke(SsqdVO ssqdVO, AnalysisContext analysisContext) {
  19.         //业务判断
  20.         System.out.println("***"+ssqdVO+"***");
  21.         list.add(ssqdVO);
  22. //        if (list.size() > 100) {
  23. //            wjgbpclService.saveData(list);//保存到数据库
  24. //            list = ListUtils.newArrayListWithExpectedSize(100);
  25. //        }
  26.     }
  27.     @Override
  28.     public void doAfterAllAnalysed(AnalysisContext analysisContext) {
  29.         if (CollectionUtils.isNotEmpty(list)) {
  30.             System.out.println("***结束***");
  31.             System.out.println(list);
  32.             iSsqdService.saveData(list);
  33.         }else{
  34.             throw new BusinException("500","导入的文件为空,请填写信息后重新导入。");
  35.         }
  36.     }
  37.     /**
  38.      * 在这里进行模板的判断
  39.      * @param headMap 存放着导入表格的表头,键是索引,值是名称
  40.      * @param context
  41.      */
  42.     @Override
  43.     public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
  44.         String isNull = "";
  45.         if (context.readRowHolder().getRowIndex() == 0) {
  46.             String[] headList = {"试纱类型","布号","支数","产地","批号","重量","备注"};
  47.             for (int i = 0; i < headList.length; i++) {
  48.                 try {
  49.                     if (!headMap.get(i).equals(headList[i])) {
  50.                         isNull = "导入模板不正确,请重新导入";
  51.                         break;
  52.                     }
  53.                 } catch (Exception e) {
  54.                     isNull = "导入模板不正确,请重新导入";
  55.                     break;
  56.                 }
  57.             }
  58.         }
  59.         if(isNull!=""){
  60.             throw new BusinException("500",isNull);
  61.         }
  62.     }
  63. }
复制代码
  实现类
  1.         @Override
  2.         public void saveData(List<SsqdVO> list) {
  3.                 //出现空的数据行,只有边框没有值-处理
  4.                 list = tableNullLineRemove(list);
  5.                 String msg = "";
  6.                 if(list.size() > 0){
  7.                         if (StringUtil.isEmpty(msg)) {
  8.                                 // 验证输入数据重复性
  9.                                 msg = checkMxList(list);
  10.                         }
  11.                         if (StringUtil.isEmpty(msg)) {
  12.                                 // excel数据插入数据库
  13.                                 List<SsqdVO> arr = new ArrayList<>(100);
  14.                                 for (int i = 0; i < list.size(); i++) {
  15.                                         SsqdVO bean= list.get(i);
  16.                                         bean = nullToString(bean);
  17.                                         arr.add(bean);
  18.                                 }
  19.                                 if (CollectionUtils.isNotEmpty(list)) {
  20.                                         if(!importAdd(list)){//导入
  21.                                                 throw new BusinException("500","导入的文件有效记录数超过1000条,请分批次多次导入");
  22.                                         }
  23.                                 }
  24.                         }
  25.                 }
  26.                 if(!StringUtil.isEmpty(msg)){
  27.                         throw new BusinException("500",msg);
  28.                 }
  29.         }
  30.         /**
  31.          * 验证输入数据重复性
  32.          * @param list
  33.          * @return
  34.          */
  35.         private String checkMxList(List<SsqdVO> list) {
  36.                 List<String> errMsgList = new ArrayList<String>();
  37.                 String msg = "";
  38.                 if (list.size() > 0) {
  39.                         // 把页面的数据进行重复性检验
  40.                         for (int i = 0; i < list.size(); i++) {
  41.                                 SsqdVO mxModel = list.get(i);
  42.                                 String PBLX = StringUtil.nullToSring(mxModel.getPBLX());
  43.                                 String BH = StringUtil.nullToSring(mxModel.getBH());
  44.                                 String ZS = StringUtil.nullToSring(mxModel.getZS());
  45.                                 String ZL = StringUtil.nullToSring(mxModel.getZL());
  46.                                 //当纱织类型,布号,支数和重量都为空,那么这条记录既不交验,也不添加
  47.                                 if(StringUtil.isEmpty(PBLX) && StringUtil.isEmpty(BH) && StringUtil.isEmpty(ZS) && StringUtil.isEmpty(ZL)){
  48.                                         continue;
  49.                                 }
  50.                                 for (int j = 1; j < list.size(); j++) {
  51.                                         if (i != j) {
  52.                                                 SsqdVO mxModelSec =  list.get(j);
  53.                                                 String PBLXsec = mxModelSec.getPBLX();
  54.                                                 String BHsec = StringUtil.nullToSring(mxModelSec.getBH());
  55.                                                 String ZSsec = StringUtil.nullToSring(mxModelSec.getZS());
  56.                                                 String ZLsec = StringUtil.nullToSring(mxModelSec.getZL());
  57.                                                 //当纱织类型,布号,支数和重量都为空,那么这条记录既不交验,也不添加
  58.                                                 if(StringUtil.isEmpty(PBLXsec) && StringUtil.isEmpty(BHsec) && StringUtil.isEmpty(ZSsec) && StringUtil.isEmpty(ZLsec)){
  59.                                                         continue;
  60.                                                 }
  61.                                                 if(PBLX.equals(PBLXsec) && "2".equals(PBLX)){
  62.                                                         if ((StringUtil.nullToSring(mxModelSec.getBH()))
  63.                                                                         .equals(StringUtil.nullToSring(mxModel.getBH()))
  64.                                                                         && (StringUtil.nullToSring(mxModelSec.getZS()))
  65.                                                                         .equals(StringUtil.nullToSring(mxModel.getZS()))
  66.                                                                         && (StringUtil.nullToSring(mxModelSec.getZL()))
  67.                                                                         .equals(StringUtil.nullToSring(mxModel.getZL()))
  68.                                                                         && (StringUtil.nullToSring(mxModelSec.getSC()))
  69.                                                                         .equals(StringUtil.nullToSring(mxModel.getSC()))
  70.                                                                         && (StringUtil.nullToSring(mxModelSec.getSH()))
  71.                                                                         .equals(StringUtil.nullToSring(mxModel.getSH()))
  72.                                                                         && (StringUtil.nullToSring(mxModelSec.getGY()))
  73.                                                                         .equals(StringUtil.nullToSring(mxModel.getGY()))) {
  74.                                                                 msg="导入文档第" + (i+1) + "行数据记录与第" + (j+1)
  75.                                                                                 + "行数据记录重复</br>";
  76.                                                                 /*errMsgList.add("导入文档第" + (i+1) + "行数据记录与第" + j
  77.                                                                                 + "行数据记录重复</br>");*/
  78.                                                         }
  79.                                                 } else {
  80.                                                         if ((StringUtil.nullToSring(mxModelSec.getBH()))
  81.                                                                         .equals(StringUtil.nullToSring(mxModel.getBH()))
  82.                                                                         && (StringUtil.nullToSring(mxModelSec.getZS()))
  83.                                                                         .equals(StringUtil.nullToSring(mxModel.getZS()))
  84.                                                                         && (StringUtil.nullToSring(mxModelSec.getZL()))
  85.                                                                         .equals(StringUtil.nullToSring(mxModel.getZL()))) {
  86.                                                                 msg="导入文档第" + (i+1) + "行数据记录与第" + (j+1)
  87.                                                                                 + "行数据记录重复</br>";
  88.                                                                 /*errMsgList.add("导入文档第" + (i+1) + "行数据记录与第" + j
  89.                                                                                 + "行数据记录重复</br>")*/;
  90.                                                         }
  91.                                                 }
  92.                                         }
  93.                                 }
  94.                         }
  95.                 }
  96.                 return msg;
  97.         }
  98.         private Boolean importAdd(List<SsqdVO> list) {
  99.                 UserDTO userBean = UserUtil.getUserInfo();
  100.                 int index = 0 ;
  101.                 List <Map <String, String>> addList = new ArrayList <Map <String, String>>();
  102.                 for (int i = 0; i < list.size(); i++) {
  103.                         SsqdVO entry = list.get(i);
  104.                 //保存的处理逻辑
  105.                
  106.                 }
  107.                 iSsqdDao.insertSSQD(addList);
  108.                 iSsqdDao.insertSSRZGY(addList);
  109.                 return true;
  110.         }
  111.         private SsqdVO nullToString(SsqdVO params) {
  112.                 Map<String,Object> map = new HashMap<>();
  113.                 Field[] fields = params.getClass().getDeclaredFields();
  114.                 try {
  115.                         for (Field field : fields
  116.                         ) {
  117.                                 //设置允许通过反射访问私有变量
  118.                                 field.setAccessible(true);
  119.                                 map.put(field.getName(),field.get(params)==null? "":field.get(params));
  120.                         }
  121.                 }catch (Exception e){
  122.                         e.printStackTrace();
  123.                 }
  124.                 return MapUntil.mapToBean(map,new SsqdVO());
  125.         }
  126.         private List<SsqdVO> tableNullLineRemove(List<SsqdVO> list) {
  127.                 List<SsqdVO> l = new ArrayList<>();
  128.                 //当纱织类型,布号,支数和重量都为空,那么这条记录既不交验,也不添加
  129.                 for (SsqdVO model:list
  130.                 ) {
  131.                         if(model.getPBLX()==null && model.getBH() ==null&&model.getZS()==null &&model.getZL()==null){
  132.                                 continue;
  133.                         }else{
  134.                                 l.add(model);
  135.                         }
  136.                 }
  137.                 return l;
  138.         }
复制代码
  SQL  oracle数据库批量新增
  1.     <insert id="insertSSQD" parameterType="list">
  2.         insert all
  3.         <foreach collection="list" item="item">
  4.         <![CDATA[
  5.         into T_JS_SYGL_SSQD
  6.         (
  7.         SSQDID,
  8.         RSQDBH,
  9.         BH,
  10.         PBLX,
  11.         PBMC,
  12.         ZS,
  13.         CREATER,
  14.         CRENAME,
  15.         UPDATER,
  16.         BMXXID,
  17.         BMMC,
  18.         JGXXID,
  19.         JGMC,
  20.         ZTXXID,
  21.         ZTMC
  22.         ]]>
  23.         <if test=" item.ZL != null and item.ZL != '' ">,ZL </if>
  24.         <if test=" item.SH != null and item.SH != '' ">,SH </if>
  25.         <if test=" item.ZFMYQ != null and item.ZFMYQ != '' ">,ZFMYQ </if>
  26.         <if test=" item.XSYQ != null and item.XSYQ != '' ">,XSYQ </if>
  27.         <if test=" item.SG != null and item.SG != '' ">,SG </if>
  28.         <if test=" item.REMARK != null and item.REMARK != '' ">,REMARK </if>
  29.         <if test=" item.CD != null and item.CD != '' ">,CD </if>
  30.         <if test=" item.PH != null and item.PH != '' ">,PH </if>
  31.         <if test=" item.SC != null and item.SC != '' ">,SC </if>
  32.         ) VALUES(
  33.         <![CDATA[
  34.         #{item.SSQDID},
  35.         #{item.RSQDBH},
  36.         #{item.BH},
  37.         #{item.PBLX},
  38.         #{item.PBMC},
  39.         #{item.ZS},
  40.         #{item.CREATER},
  41.         #{item.CRENAME},
  42.         #{item.UPDATER},
  43.         #{item.BMXXID},
  44.         #{item.BMMC},
  45.         #{item.JGXXID},
  46.         #{item.JGMC},
  47.         #{item.ZTXXID},
  48.         #{item.ZTMC}
  49.         ]]>
  50.         <if test=" item.ZL != null and item.ZL != '' ">,#{item.ZL} </if>
  51.         <if test=" item.SH != null and item.SH != '' ">,#{item.SH} </if>
  52.         <if test=" item.ZFMYQ != null and item.ZFMYQ != '' ">,#{item.ZFMYQ} </if>
  53.         <if test=" item.XSYQ != null and item.XSYQ != '' ">,#{item.XSYQ} </if>
  54.         <if test=" item.SG != null and item.SG != '' ">,#{item.SG} </if>
  55.         <if test=" item.REMARK != null and item.REMARK != '' ">,#{item.REMARK} </if>
  56.         <if test=" item.CD != null and item.CD != '' ">,#{item.CD} </if>
  57.         <if test=" item.PH != null and item.PH != '' ">,#{item.PH} </if>
  58.         <if test=" item.SC != null and item.SC != '' ">,#{item.SC} </if>
  59.         )
  60.         </foreach>
  61.         select * from dual
  62.     </insert>
复制代码
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

郭卫东

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表