前言:通过对上传Excel文件的读取,实现将Excel内容插入到数据库,解决了数据库大批量数据手动添加的过程。
关键词:文件上传,Excel,MySql数据库
一、工具类
此Excel工具类的作用为,读取Excel的内容,传回一个List集合,集合中存储的是Map集合,List的长度为表格的行数(不含表头);Map中的Key为表头,Value为单元格值;形参path为传入的Excel的绝对路径,参考我上一篇文章:前端文件上传及后端接收(el-upload标签的使用)
使用的依赖:
<!--excel相关-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
package com.han.common.util;
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class Excel {
// 读Excel,返回包含map的集合
public static List<Map<Object, Object>> getExcel(String path) throws Exception {
// 读取excel中数据。
InputStream inputStream = new FileInputStream(path);
// 工作册对象
Workbook workbook = WorkbookFactory.create(inputStream);
// 工作簿对象,第一张表
Sheet sheet = workbook.getSheetAt(0);
// 第一行
Row firstRow = sheet.getRow(0);
// 列数
int column = firstRow.getPhysicalNumberOfCells();
// 获取表头,放入集合
ArrayList<String> strings = new ArrayList<>();
for (int i = 0; i < column; i++) {
Cell cell = firstRow.getCell(i);
strings.add(i, cell.getStringCellValue());
}
// 获取行数
int rows = sheet.getPhysicalNumberOfRows();
//数据存入map中
ArrayList<Map<Object, Object>> list = new ArrayList<>();
// 遍历每行
for (int i = 1; i < rows; i++) {
HashMap<Object, Object> map = new HashMap<>();
// 获取当前行
Row row = sheet.getRow(i);
// 遍历每列
for (int j = 0; j < column; j++) {
// 每个单元格
Cell cell = row.getCell(j);
// 获取单元格数据类型
int cellType = cell.getCellType();
Object value = null;
if (cellType == Cell.CELL_TYPE_STRING) {
// 字符串类型
value = cell.getStringCellValue();
} else if (cellType == Cell.CELL_TYPE_NUMERIC) {
// 数字格式
if (DateUtil.isCellDateFormatted(cell)) {
// 日期类型
Date dateCellValue = cell.getDateCellValue();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
value = dateFormat.format(dateCellValue);
} else {
double t = cell.getNumericC