赞
踩
项目代码: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添加依赖,完整代码如下
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>1.5.2.RELEASE</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
- <groupId>com.xue</groupId>
- <artifactId>springbootImportExcel</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <name>springbootImportExcel</name>
- <description>Demo project for Spring Boot</description>
-
- <properties>
- <java.version>1.8</java.version>
- <maven-jar-plugin.version>3.0.0</maven-jar-plugin.version>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-jpa</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-thymeleaf</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>1.3.0</version>
- </dependency>
-
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <version>1.2</version>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.1.17</version>
- </dependency>
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi</artifactId>
- <version>3.15</version>
- </dependency>
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi-ooxml</artifactId>
- <version>3.15</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>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
-
- </project>

6.配置文件application.properties
-
- #mysql
- spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springimport_excel?&useUnicode=true&characterEncoding=UTF-8
- spring.datasource.username=root
- spring.datasource.password=123456
-
- #druid
- spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
- #dao
- mybatis.type-aliases-package==com.xue.repository.dao
- mybatis.mapper-locations=classpath*:com/xue/repository/mapper/*.xml
- #thymeleaf
- #spring.thymeleaf.prefix=classpath:/templates/
- #spring.thymeleaf.suffix=.jsp
- spring.thymeleaf.encoding=UTF-8

7.创建controller层,创建UserController
- package com.xue.controller;
-
- import javax.servlet.http.HttpSession;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.multipart.MultipartFile;
-
- import com.xue.service.UserService;
-
- @Controller
- public class UserController {
-
- @Autowired
- private UserService userService;
-
- /**
- * 页面
- */
- @RequestMapping("/index")
- public String index(){
-
- return "index";
- }
-
- /**
- * 导入excel
- */
- @RequestMapping("/import")
- @ResponseBody
- public String excelImport(@RequestParam(value="filename")MultipartFile file,HttpSession session){
-
- // String fileName = file.getOriginalFilename();
-
- int result = 0;
-
- try {
- result = userService.addUser(file);
- } catch (Exception e) {
-
- e.printStackTrace();
- }
-
- if(result > 0){
- return "excel文件数据导入成功!";
- }else{
- return "excel数据导入失败!";
- }
-
- }
-
-
- }

8.创建service层,创建接口UserService与接口实现类UserServiceImpl
UserService
- package com.xue.service;
-
- import org.springframework.web.multipart.MultipartFile;
-
- public interface UserService {
- // 增加用户
- public int addUser(MultipartFile file) throws Exception;
-
- }
UserServiceImpl
- package com.xue.service.Impl;
-
- import java.io.InputStream;
- import java.util.ArrayList;
- import java.util.List;
-
- import org.apache.poi.hssf.usermodel.HSSFWorkbook;
- import org.apache.poi.ss.usermodel.Cell;
- import org.apache.poi.ss.usermodel.Row;
- import org.apache.poi.ss.usermodel.Sheet;
- import org.apache.poi.ss.usermodel.Workbook;
- import org.apache.poi.xssf.usermodel.XSSFWorkbook;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import org.springframework.web.multipart.MultipartFile;
-
- import com.xue.entity.model.User;
- import com.xue.repository.dao.UserMapper;
- import com.xue.service.UserService;
- import com.xue.transcation.MyException;
- @Service
- public class UserServiceImpl implements UserService {
-
- @Autowired
- private UserMapper userMapper;
-
- @Override
- public int addUser(MultipartFile file) throws Exception{
-
- int result = 0;
- // 存放excel表中所有user细腻
- List<User> userList = new ArrayList<>();
- /**
- *
- * 判断文件版本
- */
- String fileName = file.getOriginalFilename();
- String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
-
- InputStream ins = file.getInputStream();
-
- Workbook wb = null;
-
- if(suffix.equals("xlsx")){
-
- wb = new XSSFWorkbook(ins);
-
- }else{
- wb = new HSSFWorkbook(ins);
- }
- /**
- * 获取excel表单
- */
- Sheet sheet = wb.getSheetAt(0);
-
-
- /**
- * line = 2 :从表的第三行开始获取记录
- *
- */
- if(null != sheet){
-
- for(int line = 2; line <= sheet.getLastRowNum();line++){
-
- User user = new User();
-
- Row row = sheet.getRow(line);
-
- if(null == row){
- continue;
- }
- /**
- * 判断单元格类型是否为文本类型
- */
- if(1 != row.getCell(0).getCellType()){
- throw new MyException("单元格类型不是文本类型!");
- }
-
- /**
- * 获取第一个单元格的内容
- */
- String username = row.getCell(0).getStringCellValue();
-
- row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
- /**
- * 获取第二个单元格的内容
- */
-
- String password = row.getCell(1).getStringCellValue();
-
- user.setUsername(username);
- user.setPassword(password);
- userList.add(user);
-
- }
-
- for(User userInfo:userList){
-
- /**
- * 判断数据库表中是否存在用户记录,若存在,则更新,不存在,则保存记录
- */
- String name = userInfo.getUsername();
-
- int count = userMapper.selectUser(name);
-
- if(0 == count){
- result = userMapper.addUser(userInfo);
- }else{
- result = userMapper.updateUser(userInfo);
- }
-
-
-
- }
- }
-
- return result;
- }
-
-
-
- }

9.编辑dao层UserMapper.java与UserMapper.xml文件最后添加:
UserMapper.java
- // 增
- int addUser(User user);
- // 查
- int selectUser(String username);
- // 改
- int updateUser(User user);
UserMapper.xml
- <insert id="addUser" parameterType="com.xue.entity.model.User" >
- insert into user(username,password) values(#{username},#{password})
- </insert>
- <select id="selectUser" resultType="java.lang.Integer">
- select count(*) from user where username=#{username}
- </select>
- <update id="updateUser" parameterType="com.xue.entity.model.User" >
- update user set password = #{password} where username = #{username}
- </update>
10.创建自定义异常类MyException
- package com.xue.transcation;
-
- public class MyException extends RuntimeException {
-
- private static final long serialVersionId = 1L;
-
- public MyException(String message) {
- super(message);
- // TODO Auto-generated constructor stub
- }
- }
11.编辑主程序类
- package com.xue;
-
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
-
- @SpringBootApplication
- @MapperScan("com.xue.repository.dao")
- public class SpringbootImportExcelApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(SpringbootImportExcelApplication.class, args);
- }
-
- }
12.创建html页面index.html
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8"/>
- <title>Insert title here</title>
- </head>
- <body>
- <h1>导入EXCEL</h1>
- <br/>
- <form class="form-horizontal" id="form_table" action="/import" enctype="multipart/form-data" method="post">
- <button type="submit" class="btn btn-primary">导入</button>
- <input class="form-input" type="file" name="filename"></input>
- </form>
- </body>
- </html>
13.至此项目代码完成,在浏览器输入localhost:8080/index,上传文件,导入:
14.查看数据库记录
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。