excel文件导入 JAVA 后台写

增加Maven坐标:

	
		
    		org.apache.poi
    		poi
    		3.17
		
		
		    org.apache.poi
		    poi-ooxml
		    3.17
		

修改VUE请求头:


postUpload(url, data) {
    //data.append('ticket', user(null))
    return new Promise((resolve, reject) => {
      axiosUpload
        .post(url, data, { headers: { 'Content-Type': 'multipart/form-data' } })
        .then(
          res => {
            if (res.res === 'failed') {
              if (res.code === 'encrypt') {
                // 转到无权限页
                // console.log('触发无权限')
                _this.$router.push('/encrypt')
              } else if (res.code === 'no-encrypt') {
                // console.log('触发重新登录')
                // 转到登录页(redirect)
                MessageBox.alert('登录信息已失效,请重新登录!', '提示', {
                  confirmButtonText: '确定',
                  // cancelButtonText: '',
                  type: 'warning'
                })
                  .then(() => {
                    _this.$router.push('/login')
                  })
                  .catch(() => {
                    _this.$router.push('/login')
                  })
              } else {
                resolve(res)
              }
            } else {
              resolve(res)
            }
          },
          err => {
            reject(err)
          }
        )
    })
  },

export default {
  post(url, data) {
    console.log('post request url', url)
    return service({
      method: 'post',
      url,
      params: data
    })
  },
或者用

 upLoadFile(url, data) {
    console.log('upLoad request url', rul)
    return axiosx.post(url, data, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  }

JAVA:

	@ApiOperation(value = "导入国家字典信息", notes = "导入国家字典信息")
	@ApiImplicitParam(name = "ticket", value = "用户标识", required = true, dataType = "String", paramType = "form")
	@PostMapping(value = "/importCountyExcelFile" )
	 public void importCountyExcelFile(HttpServletRequest request, HttpServletResponse response,
			 @ApiParam(value="文件",required=true) @RequestPart MultipartFile file)  {
			ServletCom com = new ServletCom(request, response);
	        List> resultList =new ArrayList>();
	        List> tempList =new ArrayList>();
	        Map> codeMap =new HashMap>();
	        Map> nameMap =new HashMap>();
	        Map> eNameMap =new HashMap>();
	        Map resultInfo = Maps.newHashMap();
	        try{
	            InputStream orgExcelFileIS =file.getInputStream();
	            Workbook hssfWorkbook = WorkbookFactory.create(orgExcelFileIS);//new XSSFWorkbook(orgExcelFileIS);
	            Sheet hssfSheet = hssfWorkbook.getSheetAt(0);
	            int count =0;
	            // 循环取出excel 每行数据,进行验证处理
            	for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
	                int flag = 0;
	                Row hssfRow = hssfSheet.getRow(rowNum);
	                Map m = Maps.newHashMap();
	                // 编码
	                Cell  countryCode = hssfRow.getCell(0);
	                String code =  getCellValue(countryCode);
	                if (!StringUtils.isEmpty(code)) {
	                    m.put("code",code);
	                    flag++;
	                    count++;
	                }
	                // 国家名称
	                Cell countryName = hssfRow.getCell(1);
	                String name =  getCellValue(countryName);
	                if (!StringUtils.isEmpty(name)) {
	                    m.put("name",name);
	                    flag++;
	                }
	                //英文名
	                Cell eNmae = hssfRow.getCell(2);
	                String eName =  getCellValue(eNmae);
	                if (!StringUtils.isEmpty(eName)) {
	                    m.put("eName",eName);
	                    flag++;
	                }
	                m.put("rowNum",String.valueOf(rowNum+1));
	                if(flag==3){
	                    tempList.add(m);
	                    codeMap.put(m.get("code"),m);
	                    nameMap.put(m.get("name"),m);
	                    eNameMap.put(m.get("eName"),m);
	                }
	            }
            	// 准备做数据校验
            	 StringBuilder errorMsg = new StringBuilder();
	            List countyCodeList = new ArrayList();
		        for(Mapm:tempList){
		        	countyCodeList.add(m.get("code"));
		        }
		        
		        if(countyCodeList.size()<=0) {
		        	resultInfo.put("code","00000");
	            	resultInfo.put("msgError","没有可上传的数据");
	            	 com.renderJson(resultInfo);
		        	return ;
		        }
		        if(count > 301) {
		        	resultInfo.put("code","00000");
	            	resultInfo.put("msgError","单次最多只能上传300条数据");
	            	 com.renderJson(resultInfo);
		        	return ;
		        }
		        //  验证编码是否重复
		        // 由于数据量特别小,不超过200条,所以全表撸了,减少多次根据条件操作数据库,并且减少写循环
		        List> dataAll =  iCountryMsgService.findByAll();
		        if(dataAll!=null){
		            for(Map m:dataAll){
		            		if(codeMap.get(m.get("code"))!=null) {
		            		    errorMsg.append("第"+codeMap.get(m.get("code")).get("rowNum")+"行,国家编码重复.");
		            		}
							if(nameMap.get(m.get("name"))!=null) {
								errorMsg.append("第"+nameMap.get(m.get("name")).get("rowNum")+"行,国家名称重复.");       			
							}
							if(eNameMap.get(m.get("eName"))!=null) {
								errorMsg.append("第"+eNameMap.get(m.get("eName")).get("rowNum")+"行,英文名称重复.");
							}
		            }
		            if(errorMsg.length()>0){
			             resultInfo.put("code","00001");
			             resultInfo.put("errorMsg",errorMsg.toString());
			             com.renderJson(resultInfo);
			             return;
			         }
		        }
		        // 正则校验格式
		        // 编码
			    Pattern p1 = Pattern.compile("^((?!_)(?!.*?_$)[a-zA-Z0-9_]|_(?!_){1,10}$");
		        // 中文最多输入十个字
		        Pattern p2 = Pattern.compile("^[\\u4e00-\\u9fa5]{1,10}$");
		        // 英文
			    Pattern p3 = Pattern.compile("^[a-zA-Z]{1,20}$");
			    
			    
		        for(Map m:tempList) {
		        	int a = 0;
		        	if(!p1.matcher(m.get("code")).matches()){
		                errorMsg.append("第"+m.get("rowNum")+"行,国家编码格式或长度不正确!");
		                a++;
		            }
		        	if(!p2.matcher(m.get("name")).matches()){
		                errorMsg.append("第"+m.get("rowNum")+"行,国家名称格式或长度不正确!");
		                a++;
		            }
		        	if(!p3.matcher(m.get("eName")).matches()){
		                errorMsg.append("第"+m.get("rowNum")+"行,英文名称格式或长度不正确!");
		                a++;
		            }
		        	if(a==0) {
		        		String id = iSequenceService.generate19(Constants.CENTER_ID);
		        		m.put("id", id);
		        		resultList.add(m);
		        	}
		        }
		       
		         if(errorMsg.length()>0){
		             resultInfo.put("code","00001");
		             resultInfo.put("errorMsg",errorMsg.toString());
		         }else{
		        	 
		        	 int a = iCountryMsgService.insertBatchInsert(resultList);
		        	 
		             resultInfo.put("data",a);
		             resultInfo.put("length",resultList.size());
		         	 resultInfo.put(Constants.RESULT, Constants.SUCCESS);
				  	 resultInfo.put(Cons.RESULT_MSG, Constants.B0001);
		         }
		  
	        }catch (Exception e){
	            e.printStackTrace();
	            resultInfo.put(Constants.RESULT, Cons.FAILED);
	            resultInfo.put(Cons.RESULT_MSG, Constants.S0005);
	        }
	        com.renderJson(resultInfo);
	        
	}

	@SuppressWarnings("deprecation")
	private String getCellValue(Cell cell) {
		String result = "";
		if (cell != null) {
			switch (cell.getCellType()) {
			case Cell.CELL_TYPE_STRING:
				if (!StringUtils.isEmpty(cell.getStringCellValue())) {
					result = cell.getStringCellValue();
				}
				break;
			case Cell.CELL_TYPE_NUMERIC:
				result = String.valueOf((int) cell.getNumericCellValue());
			}
		}
		return result;
	}

VUE:







 

你可能感兴趣的:(VUE,JAVA)