項目代碼: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.查看數據庫記錄