当前位置:   article > 正文

springboot-导入excel数据存入数据库_boot+jpa项目实现excel的导入并写入数据库当中

boot+jpa项目实现excel的导入并写入数据库当中

项目代码:https://github.com/snowlavenderlove/springbootImportExcel.git

1.创建数据库springimport_excel,并创建表user

2.创建excel,内容如下

3.官网:https://start.spring.io/创建 项目springbootImportExcel,官网创建项目博文:https://blog.csdn.net/qq_37231511/article/details/90669242

4.通过mybatis-generator自动生成代码,mybatis-generator自动代码生成博文:

https://blog.csdn.net/qq_37231511/article/details/90692784,生成的代码放到项目中,如图

5.pom.xml添加依赖,完整代码如下

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>1.5.2.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.xue</groupId>
  12. <artifactId>springbootImportExcel</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>springbootImportExcel</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. <maven-jar-plugin.version>3.0.0</maven-jar-plugin.version>
  19. </properties>
  20. <dependencies>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-data-jpa</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-web</artifactId>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.mybatis.spring.boot</groupId>
  35. <artifactId>mybatis-spring-boot-starter</artifactId>
  36. <version>1.3.0</version>
  37. </dependency>
  38. <dependency>
  39. <groupId>mysql</groupId>
  40. <artifactId>mysql-connector-java</artifactId>
  41. <scope>runtime</scope>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.springframework.boot</groupId>
  45. <artifactId>spring-boot-starter-test</artifactId>
  46. <scope>test</scope>
  47. </dependency>
  48. <dependency>
  49. <groupId>commons-logging</groupId>
  50. <artifactId>commons-logging</artifactId>
  51. <version>1.2</version>
  52. </dependency>
  53. <dependency>
  54. <groupId>com.alibaba</groupId>
  55. <artifactId>druid</artifactId>
  56. <version>1.1.17</version>
  57. </dependency>
  58. <dependency>
  59. <groupId>org.apache.poi</groupId>
  60. <artifactId>poi</artifactId>
  61. <version>3.15</version>
  62. </dependency>
  63. <dependency>
  64. <groupId>org.apache.poi</groupId>
  65. <artifactId>poi-ooxml</artifactId>
  66. <version>3.15</version>
  67. </dependency>
  68. <dependency>
  69. <groupId>commons-fileupload</groupId>
  70. <artifactId>commons-fileupload</artifactId>
  71. <version>1.3.1</version>
  72. </dependency>
  73. <dependency>
  74. <groupId>commons-io</groupId>
  75. <artifactId>commons-io</artifactId>
  76. <version>2.4</version>
  77. </dependency>
  78. </dependencies>
  79. <build>
  80. <plugins>
  81. <plugin>
  82. <groupId>org.springframework.boot</groupId>
  83. <artifactId>spring-boot-maven-plugin</artifactId>
  84. </plugin>
  85. </plugins>
  86. </build>
  87. </project>

6.配置文件application.properties

  1. #mysql
  2. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  3. spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springimport_excel?&useUnicode=true&characterEncoding=UTF-8
  4. spring.datasource.username=root
  5. spring.datasource.password=123456
  6. #druid
  7. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  8. #dao
  9. mybatis.type-aliases-package==com.xue.repository.dao
  10. mybatis.mapper-locations=classpath*:com/xue/repository/mapper/*.xml
  11. #thymeleaf
  12. #spring.thymeleaf.prefix=classpath:/templates/
  13. #spring.thymeleaf.suffix=.jsp
  14. spring.thymeleaf.encoding=UTF-8

7.创建controller层,创建UserController

  1. package com.xue.controller;
  2. import javax.servlet.http.HttpSession;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RequestParam;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8. import org.springframework.web.multipart.MultipartFile;
  9. import com.xue.service.UserService;
  10. @Controller
  11. public class UserController {
  12. @Autowired
  13. private UserService userService;
  14. /**
  15. * 页面
  16. */
  17. @RequestMapping("/index")
  18. public String index(){
  19. return "index";
  20. }
  21. /**
  22. * 导入excel
  23. */
  24. @RequestMapping("/import")
  25. @ResponseBody
  26. public String excelImport(@RequestParam(value="filename")MultipartFile file,HttpSession session){
  27. // String fileName = file.getOriginalFilename();
  28. int result = 0;
  29. try {
  30. result = userService.addUser(file);
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. }
  34. if(result > 0){
  35. return "excel文件数据导入成功!";
  36. }else{
  37. return "excel数据导入失败!";
  38. }
  39. }
  40. }

8.创建service层,创建接口UserService与接口实现类UserServiceImpl

 UserService

  1. package com.xue.service;
  2. import org.springframework.web.multipart.MultipartFile;
  3. public interface UserService {
  4. // 增加用户
  5. public int addUser(MultipartFile file) throws Exception;
  6. }

 UserServiceImpl

  1. package com.xue.service.Impl;
  2. import java.io.InputStream;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  6. import org.apache.poi.ss.usermodel.Cell;
  7. import org.apache.poi.ss.usermodel.Row;
  8. import org.apache.poi.ss.usermodel.Sheet;
  9. import org.apache.poi.ss.usermodel.Workbook;
  10. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.stereotype.Service;
  13. import org.springframework.web.multipart.MultipartFile;
  14. import com.xue.entity.model.User;
  15. import com.xue.repository.dao.UserMapper;
  16. import com.xue.service.UserService;
  17. import com.xue.transcation.MyException;
  18. @Service
  19. public class UserServiceImpl implements UserService {
  20. @Autowired
  21. private UserMapper userMapper;
  22. @Override
  23. public int addUser(MultipartFile file) throws Exception{
  24. int result = 0;
  25. // 存放excel表中所有user细腻
  26. List<User> userList = new ArrayList<>();
  27. /**
  28. *
  29. * 判断文件版本
  30. */
  31. String fileName = file.getOriginalFilename();
  32. String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
  33. InputStream ins = file.getInputStream();
  34. Workbook wb = null;
  35. if(suffix.equals("xlsx")){
  36. wb = new XSSFWorkbook(ins);
  37. }else{
  38. wb = new HSSFWorkbook(ins);
  39. }
  40. /**
  41. * 获取excel表单
  42. */
  43. Sheet sheet = wb.getSheetAt(0);
  44. /**
  45. * line = 2 :从表的第三行开始获取记录
  46. *
  47. */
  48. if(null != sheet){
  49. for(int line = 2; line <= sheet.getLastRowNum();line++){
  50. User user = new User();
  51. Row row = sheet.getRow(line);
  52. if(null == row){
  53. continue;
  54. }
  55. /**
  56. * 判断单元格类型是否为文本类型
  57. */
  58. if(1 != row.getCell(0).getCellType()){
  59. throw new MyException("单元格类型不是文本类型!");
  60. }
  61. /**
  62. * 获取第一个单元格的内容
  63. */
  64. String username = row.getCell(0).getStringCellValue();
  65. row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
  66. /**
  67. * 获取第二个单元格的内容
  68. */
  69. String password = row.getCell(1).getStringCellValue();
  70. user.setUsername(username);
  71. user.setPassword(password);
  72. userList.add(user);
  73. }
  74. for(User userInfo:userList){
  75. /**
  76. * 判断数据库表中是否存在用户记录,若存在,则更新,不存在,则保存记录
  77. */
  78. String name = userInfo.getUsername();
  79. int count = userMapper.selectUser(name);
  80. if(0 == count){
  81. result = userMapper.addUser(userInfo);
  82. }else{
  83. result = userMapper.updateUser(userInfo);
  84. }
  85. }
  86. }
  87. return result;
  88. }
  89. }

9.编辑dao层UserMapper.java与UserMapper.xml文件最后添加:

UserMapper.java

  1. // 增
  2. int addUser(User user);
  3. // 查
  4. int selectUser(String username);
  5. // 改
  6. int updateUser(User user);

UserMapper.xml

  1. <insert id="addUser" parameterType="com.xue.entity.model.User" >
  2. insert into user(username,password) values(#{username},#{password})
  3. </insert>
  4. <select id="selectUser" resultType="java.lang.Integer">
  5. select count(*) from user where username=#{username}
  6. </select>
  7. <update id="updateUser" parameterType="com.xue.entity.model.User" >
  8. update user set password = #{password} where username = #{username}
  9. </update>

 10.创建自定义异常类MyException

  1. package com.xue.transcation;
  2. public class MyException extends RuntimeException {
  3. private static final long serialVersionId = 1L;
  4. public MyException(String message) {
  5. super(message);
  6. // TODO Auto-generated constructor stub
  7. }
  8. }

11.编辑主程序类

  1. package com.xue;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. @SpringBootApplication
  6. @MapperScan("com.xue.repository.dao")
  7. public class SpringbootImportExcelApplication {
  8. public static void main(String[] args) {
  9. SpringApplication.run(SpringbootImportExcelApplication.class, args);
  10. }
  11. }

 12.创建html页面index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8"/>
  5. <title>Insert title here</title>
  6. </head>
  7. <body>
  8. <h1>导入EXCEL</h1>
  9. <br/>
  10. <form class="form-horizontal" id="form_table" action="/import" enctype="multipart/form-data" method="post">
  11. <button type="submit" class="btn btn-primary">导入</button>
  12. <input class="form-input" type="file" name="filename"></input>
  13. </form>
  14. </body>
  15. </html>

13.至此项目代码完成,在浏览器输入localhost:8080/index,上传文件,导入:

14.查看数据库记录

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/714004
推荐阅读
相关标签
  

闽ICP备14008679号