Springboot上传excel并将表格数据导入或更新mySql数据库(转)

转自https://blog.csdn.net/xyy1028/article/details/79054749 亲测可用

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

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

  1. <dependency>
  2. <groupId>org.apache.poi </groupId>
  3. <artifactId>poi-ooxml </artifactId>
  4. <version>3.9 </version>
  5. </dependency>
  6. <dependency>
  7. <groupId>commons-fileupload </groupId>
  8. <artifactId>commons-fileupload </artifactId>
  9. <version>1.3.1 </version>
  10. </dependency>
  11. <dependency>
  12. <groupId>commons-io </groupId>
  13. <artifactId>commons-io </artifactId>
  14. <version>2.4 </version>
  15. </dependency>

2.entity实体类

  1. public class User implements Serializable {
  2. private Integer id;
  3. private String name;
  4. private String phone;
  5. private String address;
  6. private Date enrolDate;
  7. private String des;
  8. private static final long serialVersionUID = 1L;
  9. public User(Integer id, String name, String phone, String address, Date enrolDate, String des) {
  10. this.id = id;
  11. this.name = name;
  12. this.phone = phone;
  13. this.address = address;
  14. this.enrolDate = enrolDate;
  15. this.des = des;
  16. }
  17. public User() {
  18. super();
  19. }
  20. public Integer getId() {
  21. return id;
  22. }
  23. public void setId(Integer id) {
  24. this.id = id;
  25. }
  26. public String getName() {
  27. return name;
  28. }
  29. public void setName(String name) {
  30. this.name = name == null ? null : name.trim();
  31. }
  32. public String getPhone() {
  33. return phone;
  34. }
  35. public void setPhone(String phone) {
  36. this.phone = phone == null ? null : phone.trim();
  37. }
  38. public String getAddress() {
  39. return address;
  40. }
  41. public void setAddress(String address) {
  42. this.address = address == null ? null : address.trim();
  43. }
  44. public Date getEnrolDate() {
  45. return enrolDate;
  46. }
  47. public void setEnrolDate(Date enrolDate) {
  48. this.enrolDate = enrolDate;
  49. }
  50. public String getDes() {
  51. return des;
  52. }
  53. public void setDes(String des) {
  54. this.des = des == null ? null : des.trim();
  55. }
  56. @Override
  57. public boolean equals(Object that) {
  58. if ( this == that) {
  59. return true;
  60. }
  61. if (that == null) {
  62. return false;
  63. }
  64. if (getClass() != that.getClass()) {
  65. return false;
  66. }
  67. User other = (User) that;
  68. return ( this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
  69. && ( this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()))
  70. && ( this.getPhone() == null ? other.getPhone() == null : this.getPhone().equals(other.getPhone()))
  71. && ( this.getAddress() == null ? other.getAddress() == null : this.getAddress().equals(other.getAddress()))
  72. && ( this.getEnrolDate() == null ? other.getEnrolDate() == null : this.getEnrolDate().equals(other.getEnrolDate()))
  73. && ( this.getDes() == null ? other.getDes() == null : this.getDes().equals(other.getDes()));
  74. }
  75. @Override
  76. public int hashCode() {
  77. final int prime = 31;
  78. int result = 1;
  79. result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
  80. result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
  81. result = prime * result + ((getPhone() == null) ? 0 : getPhone().hashCode());
  82. result = prime * result + ((getAddress() == null) ? 0 : getAddress().hashCode());
  83. result = prime * result + ((getEnrolDate() == null) ? 0 : getEnrolDate().hashCode());
  84. result = prime * result + ((getDes() == null) ? 0 : getDes().hashCode());
  85. return result;
  86. }
  87. }

3.Controller接口

  1. @RestController
  2. @RequestMapping( "/test/")
  3. public class TestController {
  4. @Autowired
  5. private ITestService testService;
  6. @PostMapping( "/import")
  7. public boolean addUser(@RequestParam("file") MultipartFile file) {
  8. boolean a = false;
  9. String fileName = file.getOriginalFilename();
  10. try {
  11. a = testService.batchImport(fileName, file);
  12. } catch (Exception e) {
  13. e.printStackTrace();
  14. }
  15. return a;
  16. }
  17. }

4.服务层接口

  1. public interface ITestService {
  2. boolean batchImport(String fileName, MultipartFile file) throws Exception;
  3. }

5.业务层实现类

  1. @Service
  2. @Transactional(readOnly = true)
  3. public class TestServiceImpl implements ITestService {
  4. @Autowired
  5. private UserMapper userMapper;
  6. @Transactional(readOnly = false,rollbackFor = Exception.class)
  7. @Override
  8. public boolean batchImport(String fileName, MultipartFile file) throws Exception {
  9. boolean notNull = false;
  10. List<User> userList = new ArrayList<User>();
  11. if (!fileName.matches( "^.+\\.(?i)(xls)$") && !fileName.matches( "^.+\\.(?i)(xlsx)$")) {
  12. throw new MyException( "上传文件格式不正确");
  13. }
  14. boolean isExcel2003 = true;
  15. if (fileName.matches( "^.+\\.(?i)(xlsx)$")) {
  16. isExcel2003 = false;
  17. }
  18. InputStream is = file.getInputStream();
  19. Workbook wb = null;
  20. if (isExcel2003) {
  21. wb = new HSSFWorkbook(is);
  22. } else {
  23. wb = new XSSFWorkbook(is);
  24. }
  25. Sheet sheet = wb.getSheetAt( 0);
  26. if(sheet!= null){
  27. notNull = true;
  28. }
  29. User user;
  30. for ( int r = 1; r <= sheet.getLastRowNum(); r++) {
  31. Row row = sheet.getRow(r);
  32. if (row == null){
  33. continue;
  34. }
  35. user = new User();
  36. if( row.getCell( 0).getCellType() != 1){
  37. throw new MyException( "导入失败(第"+(r+ 1)+ "行,姓名请设为文本格式)");
  38. }
  39. String name = row.getCell( 0).getStringCellValue();
  40. if(name == null || name.isEmpty()){
  41. throw new MyException( "导入失败(第"+(r+ 1)+ "行,姓名未填写)");
  42. }
  43. row.getCell( 1).setCellType(Cell.CELL_TYPE_STRING);
  44. String phone = row.getCell( 1).getStringCellValue();
  45. if(phone== null || phone.isEmpty()){
  46. throw new MyException( "导入失败(第"+(r+ 1)+ "行,电话未填写)");
  47. }
  48. String add = row.getCell( 2).getStringCellValue();
  49. if(add== null){
  50. throw new MyException( "导入失败(第"+(r+ 1)+ "行,不存在此单位或单位未填写)");
  51. }
  52. Date date;
  53. if(row.getCell( 3).getCellType() != 0){
  54. throw new MyException( "导入失败(第"+(r+ 1)+ "行,入职日期格式不正确或未填写)");
  55. } else{
  56. date = row.getCell( 3).getDateCellValue();
  57. }
  58. String des = row.getCell( 4).getStringCellValue();
  59. user.setName(name);
  60. user.setPhone(phone);
  61. user.setAddress(add);
  62. user.setEnrolDate(date);
  63. user.setDes(des);
  64. userList.add(user);
  65. }
  66. for (User userResord : userList) {
  67. String name = userResord.getName();
  68. int cnt = userMapper.selectByName(name);
  69. if (cnt == 0) {
  70. userMapper.addUser(userResord);
  71. System.out.println( " 插入 "+userResord);
  72. } else {
  73. userMapper.updateUserByName(userResord);
  74. System.out.println( " 更新 "+userResord);
  75. }
  76. }
  77. return notNull;
  78. }
  79. }

6.mapper层

  1. @Mapper
  2. public interface UserMapper {
  3. void addUser(User sysUser);
  4. int updateUserByName(User sysUser);
  5. int selectByName(String name);
  6. }

7.mybatis

  1. <?xml version= "1.0" encoding= "UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace= "com.why.MyProject.mapper.UserMapper">
  4. <resultMap id= "BaseResultMap" type= "com.why.MyProject.entity.User">
  5. <constructor>
  6. <idArg column= "t_id" javaType= "java.lang.Integer" jdbcType= "INTEGER" />
  7. <arg column= "t_name" javaType= "java.lang.String" jdbcType= "VARCHAR" />
  8. <arg column= "t_phone" javaType= "java.lang.String" jdbcType= "VARCHAR" />
  9. <arg column= "t_address" javaType= "java.lang.String" jdbcType= "VARCHAR" />
  10. <arg column= "t_enrol_date" javaType= "java.util.Date" jdbcType= "TIMESTAMP" />
  11. <arg column= "t_des" javaType= "java.lang.String" jdbcType= "VARCHAR" />
  12. </constructor>
  13. </resultMap>
  14. <insert id= "addUser" parameterType= "com.why.MyProject.entity.User">
  15. insert into user
  16. (name,phone,address,enrol_date,des)
  17. values
  18. (
  19. #{name},
  20. #{phone},
  21. #{address},
  22. #{enrolDate},
  23. #{des}
  24. )
  25. </insert>
  26. <update id= "updateUserByName" parameterType= "com.why.MyProject.entity.User">
  27. update user
  28. set
  29. phone=#{phone},
  30. address=#{address},
  31. enrol_date=#{enrolDate},
  32. des=#{des}
  33. where name = #{name}
  34. </update>
  35. <select id= "selectByName" resultType= "java.lang.Integer">
  36. SELECT
  37. count(*)
  38. FROM user
  39. WHERE name=#{name}
  40. </select>
  41. </mapper>
8.数据库建表语句
  1. CREATE TABLE `user` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  3. `name` varchar(255) DEFAULT NULL,
  4. `phone` varchar(255) DEFAULT NULL,
  5. `address` varchar(255) DEFAULT NULL,
  6. `enrol_date` datetime DEFAULT NULL,
  7. `des` varchar(255) DEFAULT NULL,
  8. PRIMARY KEY (`id`)
  9. ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

9.excel示例



  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值