springboot导入excel文件信息到数据库(上传或更新)

这篇博客详细介绍了如何使用SpringBoot处理Excel文件,并进行数据校验(如手机号、邮箱),将信息导入到数据库中,同时支持更新已有数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有校验手机号和邮箱以及其他的枚举校验。可以参考

Controller :

/**
     * 导入用户数据
     * @param file
     * @return
     */
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public UserCentreResponse importUser(@RequestPart("file") FilePart file) {
        UserCentreResponse userCentreResponse = new UserCentreResponse();
        List<String> errorList = new ArrayList<>();
        String fileName = null;
        if (file != null) {
            fileName = file.filename();//getOriginalFilename();

            try {
                errorList = userService.batchImport(fileName, file);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            userCentreResponse.setValue("导入成功!", errorList);
            return userCentreResponse;
        }else {
            return userCentreResponse.setError(400, "请导入文件!");
        }
    }

Service:

/**
     * 导入用户信息
     * @param fileName
     * @param file
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> batchImport(String fileName, FilePart file) throws Exception {

        boolean notNull = false;
        List<User> userList = new ArrayList<User>();//用来存储user
        List<String> errorList = new ArrayList<>();//存储错误信息
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            errorList.add("上传文件格式不正确");
            throw new RuntimeException ("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }

        //上传的文件的临时存放目录
        String tempDir=File.pathSeparator+"tmp";
        StringBuilder tempFilePath=new StringBuilder(tempDir).append(File.pathSeparator).append(UUID.randomUUID())
                .append("_").append(fileName);

        //将上传的文件保存到临时文件
        File tempFile=new File(tempFilePath.toString())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值