Springboot上传excel并将表格数据导入或更新mySql数据库[通俗易懂]

Springboot上传excel并将表格数据导入或更新mySql数据库[通俗易懂]本文主要描述,Springboot-mybatis框架下上传excel,并将之导入mysql数据库的过程,如果用户id已存在,则进行更新修改数据库中该项信息,由于用到的是前后端分离技术,这里记录的主要是后端java部分,通过与前端接口进行对接实现功能1.在pom.xml文件中导入注解,主要利用POI<dependency><groupId>org.a…

大家好,又见面了,我是你们的朋友全栈君。

本文主要描述,Springboot-mybatis框架下上传excel,并将之导入mysql数据库的过程,如果用户id已存在,则进行更新修改数据库中该项信息,由于用到的是前后端分离技术,这里记录的主要是后端java部分,通过与前端接口进行对接实现功能

1.在pom.xml文件中导入注解,主要利用POI

<dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.9</version>
</dependency>
<dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
</dependency>
<dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
</dependency>

2.entity实体类

public class User implements Serializable {
    private Integer id;

    private String name;

    private String phone;

    private String address;

    private Date enrolDate;

    private String des;

    private static final long serialVersionUID = 1L;

    public User(Integer id, String name, String phone, String address, Date enrolDate, String des) {
        this.id = id;
        this.name = name;
        this.phone = phone;
        this.address = address;
        this.enrolDate = enrolDate;
        this.des = des;
    }

    public User() {
        super();
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone == null ? null : phone.trim();
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address == null ? null : address.trim();
    }

    public Date getEnrolDate() {
        return enrolDate;
    }

    public void setEnrolDate(Date enrolDate) {
        this.enrolDate = enrolDate;
    }

    public String getDes() {
        return des;
    }

    public void setDes(String des) {
        this.des = des == null ? null : des.trim();
    }

    @Override
    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (that == null) {
            return false;
        }
        if (getClass() != that.getClass()) {
            return false;
        }
        User other = (User) that;
        return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
            && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()))
            && (this.getPhone() == null ? other.getPhone() == null : this.getPhone().equals(other.getPhone()))
            && (this.getAddress() == null ? other.getAddress() == null : this.getAddress().equals(other.getAddress()))
            && (this.getEnrolDate() == null ? other.getEnrolDate() == null : this.getEnrolDate().equals(other.getEnrolDate()))
            && (this.getDes() == null ? other.getDes() == null : this.getDes().equals(other.getDes()));
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
        result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
        result = prime * result + ((getPhone() == null) ? 0 : getPhone().hashCode());
        result = prime * result + ((getAddress() == null) ? 0 : getAddress().hashCode());
        result = prime * result + ((getEnrolDate() == null) ? 0 : getEnrolDate().hashCode());
        result = prime * result + ((getDes() == null) ? 0 : getDes().hashCode());
        return result;
    }
}

3.Controller接口

@RestController
@RequestMapping("/test/")
public class TestController {

    @Autowired
    private ITestService testService;

    @PostMapping("/import")
    public boolean addUser(@RequestParam("file") MultipartFile file) {
        boolean a = false;
        String fileName = file.getOriginalFilename();
        try {
             a = testService.batchImport(fileName, file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  a;
    }

}

4.服务层接口

public interface ITestService {

    boolean batchImport(String fileName, MultipartFile file) throws Exception;
    
}

5.业务层实现类

@Service
@Transactional(readOnly = true)
public class TestServiceImpl implements ITestService {

    @Autowired
    private UserMapper userMapper;


    @Transactional(readOnly = false,rollbackFor = Exception.class)
    @Override
    public boolean batchImport(String fileName, MultipartFile file) throws Exception {

        boolean notNull = false;
        List<User> userList = new ArrayList<User>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new MyException("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if(sheet!=null){
            notNull = true;
        }
        User user;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }

            user = new User();
            
            if( row.getCell(0).getCellType() !=1){
                throw new MyException("导入失败(第"+(r+1)+"行,姓名请设为文本格式)");
            }
            String name = row.getCell(0).getStringCellValue();

            if(name == null || name.isEmpty()){
                throw new MyException("导入失败(第"+(r+1)+"行,姓名未填写)");
            }

            row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
            String phone = row.getCell(1).getStringCellValue();
            if(phone==null || phone.isEmpty()){
                throw new MyException("导入失败(第"+(r+1)+"行,电话未填写)");
            }
            String add = row.getCell(2).getStringCellValue();
            if(add==null){
                throw new MyException("导入失败(第"+(r+1)+"行,不存在此单位或单位未填写)");
            }

            Date date;
            if(row.getCell(3).getCellType() !=0){
                throw new MyException("导入失败(第"+(r+1)+"行,入职日期格式不正确或未填写)");
            }else{
                date = row.getCell(3).getDateCellValue();
            }

            String des = row.getCell(4).getStringCellValue();

            user.setName(name);
            user.setPhone(phone);
            user.setAddress(add);
            user.setEnrolDate(date);
            user.setDes(des);

            userList.add(user);
        }
        for (User userResord : userList) {
            String name = userResord.getName();
            int cnt = userMapper.selectByName(name);
            if (cnt == 0) {
                userMapper.addUser(userResord);
                System.out.println(" 插入 "+userResord);
            } else {
                userMapper.updateUserByName(userResord);
                System.out.println(" 更新 "+userResord);
            }
        }
        return notNull;
    }
}

6.mapper层

@Mapper
public interface UserMapper {

    void addUser(User sysUser);

    int updateUserByName(User sysUser);

    int selectByName(String name);
}

7.mybatis

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.why.MyProject.mapper.UserMapper">
  <resultMap id="BaseResultMap" type="com.why.MyProject.entity.User">
    <constructor>
      <idArg column="t_id" javaType="java.lang.Integer" jdbcType="INTEGER" />
      <arg column="t_name" javaType="java.lang.String" jdbcType="VARCHAR" />
      <arg column="t_phone" javaType="java.lang.String" jdbcType="VARCHAR" />
      <arg column="t_address" javaType="java.lang.String" jdbcType="VARCHAR" />
      <arg column="t_enrol_date" javaType="java.util.Date" jdbcType="TIMESTAMP" />
      <arg column="t_des" javaType="java.lang.String" jdbcType="VARCHAR" />
    </constructor>
  </resultMap>

  <insert id="addUser" parameterType="com.why.MyProject.entity.User">
    insert into user
    (name,phone,address,enrol_date,des)
    values
    (
    #{name},
    #{phone},
    #{address},
    #{enrolDate},
    #{des}
    )
  </insert>

  <update id="updateUserByName" parameterType="com.why.MyProject.entity.User">
    update user
    set
    phone=#{phone},
    address=#{address},
    enrol_date=#{enrolDate},
    des=#{des}
    where name = #{name}
  </update>

  <select id="selectByName" resultType="java.lang.Integer">
    SELECT
    count(*)
    FROM user
    WHERE name=#{name}
  </select>
</mapper>

8.数据库建表语句

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(255) DEFAULT NULL,
  `phone` varchar(255) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  `enrol_date` datetime DEFAULT NULL,
  `des` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

9.excel示例

Springboot上传excel并将表格数据导入或更新mySql数据库[通俗易懂]

demo地址:springboot上传excel导入到数据库完整demo(后端代码)_springboot导入excel到数据库,springboot上传excel存到数据库-Java文档类资源-CSDN下载

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/154137.html原文链接:https://javaforall.net

(0)
上一篇 2022年6月28日 上午7:16
下一篇 2022年6月28日 上午7:36


相关推荐

  • DeepSeek这波更新又超神了,90%律师不知道如何用?(附教程)

    DeepSeek这波更新又超神了,90%律师不知道如何用?(附教程)

    2026年3月15日
    3
  • 究竟什么是Java虚拟机(JVM)?

    究竟什么是Java虚拟机(JVM)?我们都知道,在Windows上,软件包后缀有exe,而苹果的MacOSX系统上没有安装exe。类似地,MacOSX系统上的软件安装包是dmg后缀,不能安装在Windows系统上。为什么不能安装不同系统上的软件,因为操作系统的底层实现是不同的。对于Windows系统,exe后缀的软件代码被编译成能被Windows系统识别的机器代码。对于MacOSX系统,最后将DMG后缀的软件代码编译为M…

    2022年7月8日
    20
  • web网页设计实例作业 我的家乡- 达州(4页) HTML+CSS+JavaScript dreamweaver作业静态HTML网页设计模板

    web网页设计实例作业 我的家乡- 达州(4页) HTML+CSS+JavaScript dreamweaver作业静态HTML网页设计模板HTML5期末大作业:家乡网站设计——我的家乡-达州(4页)HTML+CSS+JavaScriptdreamweaver作业静态HTML网页设计模板常见网页设计作业题材有个人、美食、公司、学校、旅游、电商、宠物、电器、茶叶、家居、酒店、舞蹈、动漫、明星、服装、体育、化妆品、物流、环保、书籍、婚纱、军事、游戏、节日、戒烟、电影、摄影、文化、家乡、鲜花、礼品、汽车、其他等网页设计题目,A+水平作业,可满足大学生网页大作业网页设

    2022年7月19日
    18
  • vue3 codemirror_mirror代码

    vue3 codemirror_mirror代码前言如果我们想在Web端实现在线代码编译的效果,那么需要使用组件vue-codemirror,他是将CodeMirror进行了再次封装支持代码高亮62种主题颜色,例如monokai等等支持js

    2022年7月31日
    72
  • centos6.6关闭防火墙步骤「建议收藏」

    2019独角兽企业重金招聘Python工程师标准>>>…

    2022年4月16日
    64
  • Spring事务和MySQL事务详解面试

    Spring事务和MySQL事务详解面试文章目录数据库事务事务是什么事务的四大特性 MySQL 事务隔离级别查看 MySQL 当前事务隔离级别 MySQL 默认操作模式为自动提交模式 JDBC 处理事务 Spring 事务 Spring 的事务传播 PROPAGATION REQUIREDPROP SUPPORTSPROP MANDATORYPRO REQUIRES NEWPROPAGATI NOT SUPPORTEDPRO NEVERPROPAGA NESTEDSpring 事务的隔离级别 Spring

    2026年3月26日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号