我們在前面的章節已經講了如何用jpa或者mybatis來操作mysql資料庫。這一節我們就來結合具體案例,來講解下excel表格的上傳,與excel表裡資料的識别。并把識别後的資料批量導入到mysql資料庫
所用知識點
- springboot 2.1.9
- excel檔案上傳
- excel資料批量識别
- excel資料上傳到mysql資料庫
- jpa的使用
jpa的使用我們在上一節已經給大家講過了,不知道如何建立的親,記得去翻看上一節的文章:《java入門018~springboot2使用JPA操作mysql資料庫》
一,建立一個springboot項目
1,使用idea建立springboot項目
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsISPrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdsATOfd3bkFGazxCMx8VesATMfhHLlN3XnxCMwEzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5SYiVWYmF2N5UDZ5ADOhJ2YiBjYlFDZ4MzN4gDZ0YjZ58CX2AzLchDMxIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.png)
點選finish即可
二,引入識别excel的poi 和poi-ooxml類庫
完整的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 https://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>2.1.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 操作excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
記得重新Reimport
三,建立一個controller用于接收上傳的excel檔案
完整代碼如下
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
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 java.util.List;
import java.util.Map;
/**
* 2019-10-07 18:35
* author: 程式設計小石頭
* wechat:2501902696
* desc: 把excel裡的資料儲存到mysql資料庫裡
*/
@Controller
public class ExcelController {
@GetMapping("/index")
public String index() {
return "index";
}
@RequestMapping("/uploadExcel")
@ResponseBody
public String uploadExcel(@RequestParam("file") MultipartFile file,
Map<String, Object> map) {
String name = file.getOriginalFilename();
if (name.length() < 6 || !name.substring(name.length() - 5).equals(".xlsx")) {
return "檔案格式錯誤";
}
List<ExcelBean> list = null;
try {
list = ExcelUtils.excelToShopIdList(file.getInputStream());
if (list == null || list.size() <= 0) {
return "導入的資料為空";
}
//excel的資料儲存到資料庫
try {
for (ExcelBean excel : list) {
System.out.println(excel.toString());
}
} catch (Exception e) {
System.out.println(e.getMessage());
return e.getMessage();
}
} catch (Exception e) {
System.out.println(e.getMessage());
return e.getMessage();
}
return "儲存成功";
}
}
簡單講解下上面代碼的步驟
- 1,擷取使用者上傳的excel檔案
- 2,擷取file流
- 3,把excel檔案流傳入ExcelUtils.excelToShopIdList來識别excel裡的資料
- ExcelUtils很重要,是我們識别excel的重要步驟
四,ExcelUtils類如下
package com.example.demo;
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.ss.usermodel.WorkbookFactory;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/*
* 操作excel
* */
public class ExcelUtils {
public static List<ExcelBean> excelToShopIdList(InputStream inputStream) {
List<ExcelBean> list = new ArrayList<>();
Workbook workbook = null;
try {
workbook = WorkbookFactory.create(inputStream);
inputStream.close();
//工作表對象
Sheet sheet = workbook.getSheetAt(0);
//總行數
int rowLength = sheet.getLastRowNum();
// System.out.println("總行數有多少行" + rowLength);
//工作表的列
Row row = sheet.getRow(0);
//總列數
int colLength = row.getLastCellNum();
// System.out.println("總列數有多少列" + colLength);
//得到指定的單元格
Cell cell = row.getCell(0);
for (int i = 1; i <= rowLength; i++) {
ExcelBean jiFenExcel = new ExcelBean();
row = sheet.getRow(i);
for (int j = 0; j < colLength; j++) {
//列: 0姓名 1人員編号 2餐補 3部門
cell = row.getCell(j);
// System.out.print(cell + ",");
if (cell != null) {
cell.setCellType(Cell.CELL_TYPE_STRING);
String data = cell.getStringCellValue();
data = data.trim();
// System.out.print(data);
// if (StringUtils.isNumeric(data)) {
if (j == 0) {
jiFenExcel.setName(data);
} else if (j == 1) {
jiFenExcel.setJobNum(data);
} else if (j == 2) {
jiFenExcel.setCanBu(Integer.parseInt(data));
} else if (j == 3) {
jiFenExcel.setBumen(data);
}
// }
}
}
list.add(jiFenExcel);
// System.out.println("====");
}
} catch (Exception e) {
}
return list;
}
}
五,定義一個用于上傳excel檔案的html靜态網頁
我們的index.html位于resources下的static裡
代碼如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上傳excel</title>
</head>
<body>
<h1>上傳excel檔案并存入到mysql資料庫</h1>
<form action="/uploadExcel" method="post" enctype="multipart/form-data">
<p>檔案上傳</p>
<input type="file" name="file">
<p><input type="submit" value="送出"></p>
</form>
</body>
</html>
六,編寫配置檔案
這一步是讓springboot可以直接通路我們上面第五步定義的靜态html網頁。
七,運作項目
八,識别excel表格内容。