SpringBoot+vue Excel上传解析

vue实现部分

页面按钮

<template slot="menuLeft">
              <el-button
                class="filter-item"
                type="primary"
                size="small"
                icon="el-icon-upload"
                @click="batchImport">用户导入
              </el-button>
            </template>

按钮弹窗

<el-dialog
        title="用户上传"
        :visible.sync="uploadDialog"
        width="30%"
        center>
        <avue-form :option="uploadFrom" v-model="uploadObj"
                   :upload-delete="uploadDelete"
                   :upload-before="uploadBefore"
                   :upload-after="uploadAfter"
                   :file-list="fileList"> </avue-form>
      </el-dialog>

js部分

//批量导入
      batchImport(){
        this.uploadDialog=true
      },
     //上传Excel前的文件校验`在这里插入代码片`
      uploadBefore(file, done, loading){
        console.log(file)
        let extension = file.name.split(".")[1];
        let extensionList = ["xls", "xlsx"];
        if (extensionList.indexOf(extension) < 0) {
          done()
          this.$message.warning("只能上传Excel文件");
          return false;
        }
        done()
      },
      uploadAfter(res, done, loading) {
        this.uploadDialog=false
        done()
        this.getList(this.page)
      },
      uploadError(error, column){
        this.$message.error('上传失败')
        this.uploadDialog=false
        this.getList(this.page)
        console.log(error, column)
      },
      uploadDelete(file, fileList){
        return this.$confirm(`确定移除 ?`);
      },

Java实现部分

引入pom文件

<!--Excel-->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.9</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.9</version>
		</dependency>

Controller

/**
	 * Excel 批量导入用户信息
	 * @param file
	 * @return
	 */
	@SysLog("批量导入用户信息")
	@PostMapping("/uploadUser")
	public R upload(@RequestParam("file") MultipartFile file){
    
    
		if(file==null){
    
    
			return  R.failed("请上传文件");
		}
		return userService.uploadUser(file);
	}

Service实现

@Override
	public R uploadUser(MultipartFile file) {
    
    
		try {
    
    
			InputStream is = file.getInputStream();
			String regex = "^.+\\.(?i)(xlsx)$";
			String filename = file.getOriginalFilename();
			Workbook wb;
			List<SysUser> userList=Lists.newArrayList();
			if (filename != null && filename.matches(regex)) {
    
    
				wb = new XSSFWorkbook(is);
			} else {
    
    
				wb = new HSSFWorkbook(is);
			}
			Sheet sheet = wb.getSheetAt(0);
			String[] rowList={
    
    "用户名","手机号","角色","状态","部门"};
			List<SysUserRole> userRoleList=Lists.newArrayList();
			for (Row row : sheet) {
    
    
				if (row.getRowNum() == 0) {
    
    
					if (row.getLastCellNum() != rowList.length) {
    
    
						return R.failed(CommonConstants.FAIL,"列名错误");
					}
					continue;
				}
				SysUser sysUser = new SysUser();
				String userName = row.getCell(0).getStringCellValue();
				if (StringUtils.isBlank(userName)){
    
    
					return R.failed("请填写用户名");
				}
				row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
				String phone = row.getCell(1).getStringCellValue();

				String roleName = row.getCell(2).getStringCellValue();
				if (StringUtils.isBlank(roleName)){
    
    
					return R.failed("请填写角色");
				}
				String status = row.getCell(3).getStringCellValue();
				if (StringUtils.isBlank(status)){
    
    
					return R.failed("请填写状态");
				}
				String deptName = row.getCell(4).getStringCellValue();
				if (StringUtils.isBlank(deptName)){
    
    
					return R.failed("请填写部门");
				}
				Integer deptId = getDeptName(deptName);
				List<Integer> roleList = getRoleList(roleName);
				String username = getUsername(userName);
				if (StringUtils.isNotBlank(username)){
    
    
					return R.failed("用户名【"+userName+"】已存在");
				}
				sysUser.setUsername(userName);
				boolean matches = Pattern.matches(REGEX_MOBILE, phone);
				if(!matches){
    
    
					return R.failed("用户名【"+userName+"】手机号码不正确");
				}
				sysUser.setPhone(phone);
				if (deptId!=null){
    
    
					sysUser.setDeptId(deptId);
				}
				if ("有效".equals(status)){
    
    
					sysUser.setLockFlag("0");
				}else if ("锁定".equals(status)){
    
    
					sysUser.setLockFlag("9");
				}
				sysUser.setDelFlag(CommonConstants.STATUS_NORMAL);
				sysUser.setPassword(ENCODER.encode("123456"));
				baseMapper.insert(sysUser);
				userList.add(sysUser);
				userRoleList=roleList.stream().map(roleId ->{
    
    
					SysUserRole userRole = new SysUserRole();
					userRole.setUserId(sysUser.getUserId());
					userRole.setRoleId(roleId);
					return userRole;
				}).collect(Collectors.toList());
				sysUserRoleService.saveBatch(userRoleList);
			}
		}catch (IOException e){
    
    
			return  R.failed();
		}
		return R.ok("上传成功");
	}
/**
	 * 根据部门名称获取部门ID
	 *
	 */
	public Integer getDeptName(String deptName){
    
    
		SysDept sysDept = new SysDept();
		sysDept.setName(deptName);
		SysDept sysDept1 = sysDeptService.list(Wrappers.query(sysDept))
				.stream()
				.findFirst()
				.orElse(null);
		if (sysDept1!=null && sysDept1.getDeptId()!=null){
    
    
			return sysDept1.getDeptId();
		}
		return null;
	}

	/**
	 * 根据角色名称集合查询角色ID集合
	 * @param roleName
	 * @return
	 */
	public List<Integer> getRoleList(String roleName){
    
    
		List<Integer> roleList = Lists.newArrayList();
		List<String> roleNameList= Splitter.on(",").splitToList(roleName);
		SysRole sysRole1 = new SysRole();
		for(String s :roleNameList){
    
    
			SysRole sysRole = new SysRole();
			sysRole.setRoleName(s);
			sysRole1 = sysRoleService.list(Wrappers.query(sysRole))
					.stream()
					.findFirst()
					.orElse(null);
			if (sysRole1!=null && sysRole1.getRoleId()!=null){
    
    
				roleList.add(sysRole1.getRoleId());
			}
		}
		return roleList;
	}

	/**
	 * 判断用户名是否存在
	 * @param userName
	 * @return
	 */
	public String getUsername(String userName){
    
    
		SysUser sysUser1 = new SysUser();
		sysUser1.setUsername(userName);
		SysUser sysUser2 = baseMapper.selectList(Wrappers.query(sysUser1))
				.stream()
				.findFirst()
				.orElse(null);
		if (sysUser2!=null && StringUtils.isNotBlank(sysUser2.getUsername())){
    
    
			return sysUser2.getUsername();
		}
		return null;
	}

结束 ,有不足的地方还请指教。

猜你喜欢

转载自blog.csdn.net/Sea_and_sea/article/details/107904852
今日推荐