导入功能importExcel (现成直接用)

1. 实体类字段上加 @Excel(name = "xxx"), 表示要导入的字段
    @Excel(name = "用户名称")
    private String nickName;

2. controller (post请求)
    /**
     * 导入用户数据
     *
     * @param file  文件
     * @param updateSupport  是否更新支持,如果已存在,则进行更新数据
     * @return 结果
     */
    @ApiOperation("导入用户数据")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil util = new ExcelUtil(SysUser.class);
        List userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

3. service

    /**
     * 导入用户数据
     * 
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持,如果已存在,则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空!");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("
" + successNum + "、账号 " + user.getUserName() + " 导入成功"); } else if (isUpdateSupport) { BeanValidators.validateWithException(validator, user); user.setUpdateBy(operName); this.updateUser(user); successNum++; successMsg.append("
" + successNum + "、账号 " + user.getUserName() + " 更新成功"); } else { failureNum++; failureMsg.append("
" + failureNum + "、账号 " + user.getUserName() + " 已存在"); } } catch (Exception e) { failureNum++; String msg = "
" + failureNum + "、账号 " + user.getUserName() + " 导入失败:"; failureMsg.append(msg + e.getMessage()); log.error(msg, e); } } if (failureNum > 0) { failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:"); throw new ServiceException(failureMsg.toString()); } else { successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:"); } return successMsg.toString(); }

你可能感兴趣的:(ruoyi,java)