springboot實現Excel批量導入數據庫
前言:項目開發中最容易碰到的需求即將Excel數據批量上傳到數據庫中存儲 -> Java實現,Excel數據表,MySQL數據庫,具體步驟如下…
1.新建excel表,填寫測試數據
2.新建項目工程,修改pom依賴以及application.properties如下
pom.xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<!--java對象狀態自動映射到關係數據庫中數據上-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!--實現類與xml之間的相互轉換-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.12.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>5.2.12.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--前端頁面我這裏使用了thymeleaf模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<!--使用POI讀取文件-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
application.properties
spring.datasource.username=123456
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/excel?useUnicode=true&useSSL=false&characterEncoding=UTF-8&serverTimezone=UTC
#配置通過jpa自動創建表
spring.jpa.hibernate.ddl-auto=create
#打印SQL
spring.jpa.show-sql=true
3.創建實體類,進行關係映射
啓動項目就會自動創建實體類中的表,創建完之後會發現數據庫裏的字段和實體類裏的字段順序是不一樣,是亂序狀態,是因爲hibernate源碼中用的是TreeMap存儲實體類字段,TreeMap屬性是無序的;所以解決辦法如下:
- 找到源碼文件
- 在本項目中創建一個和源碼類一樣的包結構和一樣名字的類,複製源碼文件所有代碼到新建的類中
- 將上圖標識的TreeMap 修改爲LinkedHashMap修改好之後啓動項目,會發現程序走的是新創建的類
package com.wxy.excel.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
@Entity
@Table(name = "excel")
public class Excel implements Serializable {
//serialVersionUID適用於java序列化機制
private static final long serialVersionUID = 1L;
@Id
@Column(length=36)
private String id;
@Column(length=45,nullable=false,unique=true)
private String username;
@Column(length=100,nullable=false,unique=true)
private String email;
@Column(length=45,nullable=false)
private String password;
@Column(length=45)
private String role;
//省略getter and setter 以及 constructor
4.Excel的DAO類接口,與Excel有關的持久化操作方法
package com.wxy.excel.mapper;
import com.wxy.excel.entity.Excel;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ExcelRepository extends JpaRepository<Excel,String> {
}
5.創建service層接口
Excel的Service類接口,與Excel有關的業務邏輯方法
package com.wxy.excel.service;
import org.springframework.web.multipart.MultipartFile;
public interface ExcelService {
boolean getExcel(MultipartFile file) throws Exception;
}
6.service層方法實現
Excel的Service類,與用戶信息有關的業務邏輯方法
package com.wxy.excel.service;
import com.wxy.excel.mapper.ExcelRepository;
import com.wxy.excel.entity.Excel;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.List;
@Service
public class ExcelServiceImpl implements ExcelService{
@Autowired
private ExcelRepository excelRepository;
@Override
public boolean getExcel(MultipartFile file) throws Exception {
List<Excel> list = new ArrayList<Excel>();
//1.得到上傳的表
Workbook workbook2 = WorkbookFactory.create(file.getInputStream());
//2.獲取test工作表 注意test就是excel下面的sheet名稱
Sheet sheet2 = workbook2.getSheet("test");
//3.獲取表的總行數
int num = sheet2.getLastRowNum();
//4.獲取表總列數
int col = sheet2.getRow(0).getLastCellNum();
//5.遍歷excel每一行
for (int j = 0; j <= num; j++) {
Row row1 = sheet2.getRow(j);
// 如果單元格中有數字或者其他格式的數據,則調用setCellType()轉換爲string類型
Cell cell1 = row1.getCell(0);
cell1.setCellType(CellType.STRING);
//獲取表中第i行,第2列的單元格
Cell cell2 = row1.getCell(1);
cell2.setCellType(CellType.STRING);
//獲取excel表的第i行,第3列的單元格
Cell cell3 = row1.getCell(2);
cell3.setCellType(CellType.STRING);
Cell cell4 = row1.getCell(3);
cell4.setCellType(CellType.STRING);
Cell cell5 = row1.getCell(4);
cell5.setCellType(CellType.STRING);
//這裏new 一個對象,用來裝填從頁面上傳的Excel數據,字段根據上傳的excel決定
Excel excel= new Excel();
excel.setId(cell1.getStringCellValue());
excel.setUsername(cell2.getStringCellValue());
excel.setEmail(cell3.getStringCellValue());
excel.setPassword(cell4.getStringCellValue());
excel.setRole(cell5.getStringCellValue());
list.add(excel);
System.out.println("excel"+excel);
}
excelRepository.saveAll(list);
return true;
}
}
7.Controller層實現
package com.wxy.excel.controller;
import com.wxy.excel.service.ExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class ExcelController {
@Autowired
private ExcelService excelService;
@GetMapping("/upload")
public String goUpload(){
return "upload";
}
@PostMapping("/excel")
public String upload(MultipartFile file, Model model) throws Exception {
boolean flag = excelService.getExcel(file);
if(flag){
model.addAttribute("Message", "上傳成功");
}else{
model.addAttribute("Message", "上傳失敗");
}
return "upload";
}
}
8.前端html實現
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>批量上傳</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/excel">
<input type="file" name="file" /> <input type="submit" value="上傳" />
</form>
</body>
</html>
9.項目結構圖,以及實現文件上傳效果如下
10.項目demo已經上傳到github,下載地址
https://github.com/Wangxy9527/ExcelToDatabase
或者直接clone即可:
[email protected]/ExcelToDatabase.git
https://github.com/Wangxy9527/ExcelToDatabase.git
結語:本文主要實現功能爲將Excel數據導入到數據庫中,不懂不理解或者對以上文章有疑問的小夥伴歡迎留言…