一、pom.xml文件
<properties>
<poi.version>4.1.2</poi.version>
<poi-ooxml.version>4.1.2</poi-ooxml.version>
<poi-ooxml-schemas.version>4.1.2</poi-ooxml-schemas.version>
<poi-scratchpad.version>4.1.2</poi-scratchpad.version>
<commons.io.version>2.11.0</commons.io.version>
</properties>
<dependencies>
<!-- poi -->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi-ooxml.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>${poi-ooxml-schemas.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>${poi-scratchpad.version}</version>
</dependency>
<!-- FileUtils.class for upload -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
</dependencies>
二、controller层
import com.netrust.service.ExcelTOPojoService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
@RestController
@RequestMapping("")
public class ExcelTOPojoController {
@Resource
private ExcelTOPojoService excelTOPojoService;
@PostMapping("file/upload")
public void ExcelParse(@RequestParam("file") MultipartFile file) {
excelTOPojoService.getExcelInfo(file);
}
}
三、Service层
1.Service接口
import org.springframework.web.multipart.MultipartFile;
public interface ExcelTOPojoService {
Boolean getExcelInfo(MultipartFile mFile);
}
2.ServerImpl实现类
import com.netrust.pojo.vo.EmployeeVO;
import com.netrust.service.ExcelTOPojoService;
import com.netrust.utils.ExeclUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.List;
@Slf4j
@Service
public class ExcelTOPojoImpl implements ExcelTOPojoService {
//总行数
private static int totalRows = 0;
//总条数
private static int totalCells = 0;
//错误信息接收器
private static String errorMsg;
// 路径:最好配置在yml文件中
private String path = "D:\\Excel";
/**
* 读EXCEL文件,获取信息集合 User
* @return
*/
@Override
public Boolean getExcelInfo(MultipartFile file) {
long startTime = System.currentTimeMillis();
try {
File foler = new File(path);
if (!foler.exists()) { // 判断文件是否存在
boolean mkdir = foler.mkdir();
if (!mkdir) {
log.error("此路径下创建文件目录失败:" + foler.getAbsolutePath());
}
}
// File.separator 相当于 \
// getOriginalFilename : 获取上传文件的原名
String fileNamePath = foler.getAbsolutePath() + File.separator + file.getOriginalFilename();
File dest = new File(fileNamePath);
if (!dest.exists()) {
// createNewFile():创建新文件夹,新建成功返回 true。
boolean cf = dest.createNewFile();
if (cf) {
// 文件工具类:通过输入流复制文件。
FileUtils.copyInputStreamToFile(file.getInputStream(), dest);
}
} else {
log.error("此路径下创建新文件夹失败:" + foler.getAbsolutePath());
}
List<EmployeeVO> list = (List<EmployeeVO>) ExcelUtil.getListByExcel(fileNamePath, EmployeeVO.class);
//删除文件
dest.delete();
long endTime = System.currentTimeMillis();
System.out.println("Excel导入使用了:"+ (endTime - startTime)+ " ms");
//批量插入
if (list != null && list.size() > 0) {
// 批量添加到数据库
// testMapper.insertBatch(list);
return true;
} else {
return false;
}
} catch (Exception e) {
log.error("addBatchByFile fail", e);
return false;
}
}
}
四、EmployeeVO实体类
import lombok.Data;
import java.util.Date;
/**
* 员工表
*/
@Data
public class EmployeeVO {
/**
* 工号
*/
private String jobNumber;
/**
* 姓名
*/
private String name;
/**
* 性别
*/
private String sex;
/**
* 手机号
*/
private String phoneNumber;
/**
* 证件类型(1-居民身份证,2-护照)
*/
private Integer cardType;
/**
* 身份证号
*/
private String idCard;
/**
* 职位
*/
private String position;
/**
* 部门1
*/
private String sectionOne;
/**
* 部门2
*/
private String sectionTwo;
/**
* 加入日期
*/
private Date entryDate;
}
五、ExcelUtil 工具类
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Slf4j
public class ExcelUtil {
public static List<?> getListByExcel(String path, Class<?> className) {
List<?> list = null;
// 文件类型
String filetype = path.substring(path.lastIndexOf("."));
// 读取excel文件
InputStream in = null;
// 获取工作簿
Workbook wb = null;
try {
in = new FileInputStream(path);
if (filetype.equals(".xls")) {
wb = new HSSFWorkbook(in);
} else if (filetype.equals(".xlsx")) {
wb = new XSSFWorkbook(in);
} else {
log.error("文件类型必须是xls或xlsx,file=" + path);
in.close();
return null;
}
// 获取第一个sheet集合
if (wb.getSheetAt(0) != null) {
list = getListBySheet(wb.getSheetAt(0), className);
}
in.close();
wb.close();
} catch (Exception e) {
log.error("读取文件失败" + path, e);
} finally {
try {
if (in != null) {
in.close();
}
if (wb != null) {
wb.close();
}
} catch (IOException e) {
log.error("关闭流失败" + path, e);
}
}
return list;
}
//判断row是否为空行
private static boolean isRowEmpty(Row row) {
if (null == row) {
return true;
}
int firstCellNum = row.getFirstCellNum(); //第一个列位置
int lastCellNum = row.getLastCellNum(); //最后一列位置
int nullCellNum = 0; //空列数量
for (int c = firstCellNum; c < lastCellNum; c++) {
Cell cell = row.getCell(c);
if (null == cell || BLANK == cell.getCellType()) {
nullCellNum ++;
continue;
}
DataFormatter formatter = new DataFormatter();
String cellValue = formatter.formatCellValue(row.getCell(0));//直接获取到单元格的值
if (StringUtils.isEmpty(cellValue)) {
nullCellNum ++;
}
}
//所有列都为空
if (nullCellNum == (lastCellNum - firstCellNum)) {
return true;
}
return false;
}
private static List<?> getListBySheet(Sheet sheet, Class<?> className) {
List<Object> list = new ArrayList<>();
// 总行数
// int rows = sheet.getLastRowNum(); 获取的是最后一行的编号(编号从0开始)
// getPhysicalNumberOfRows()获取的是物理行数,也就是不包括空行(隔行)的情况。
int rows = sheet.getPhysicalNumberOfRows();
for (int i = 2; i <= rows; i++) {
try {
Row row = sheet.getRow(i); // 返回当前行
// if (isRowEmpty(row)) {
// continue;
// }
// row 过滤空行。
if (null == row) {
continue;
}
int nullCellNum = 0; //空列数量
Object entity = className.newInstance(); // 通过 Class 类的 newInstance() 方法创建对象,该方法要求该 Class 对应类有无参构造方法。
Field[] fields = className.getDeclaredFields(); // getDeclaredFields ()方法,该方法是获得某个类的所有声明的字段
int fieldLength = fields.length;
for (int j = 0; j < fieldLength; j++) {
Field field = fields[j]; // 获取到类的字段
field.setAccessible(true); // 值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。
if (row == null) {
break;
}
Cell cell = row.getCell(j); // 获取单元格
// 单元格判空
if (null == cell || BLANK == cell.getCellType()) {
nullCellNum ++;
continue;
}
DataFormatter formatter = new DataFormatter();
String cellValue = formatter.formatCellValue(row.getCell(0));//直接获取到单元格的值
if (StringUtils.isEmpty(cellValue)) {
nullCellNum ++;
}
if (cell != null) {
switch (cell.getCellType()) { // 获取单元格的类型
// 数值类型
case NUMERIC: {
// 日期
if (DateUtil.isCellDateFormatted(cell)) {
field.set(entity, (cell.getDateCellValue()));
} else {
// 数值
DecimalFormat df = new DecimalFormat("0");
String str = String.valueOf(df.format(cell.getNumericCellValue()));
if (field.getType() == Integer.class) {
if (StringUtils.isNotEmpty(str)) {
String[] strs = str.split("\\.");
if (strs.length > 1 && "0".equals(strs[1])) {
str = strs[0];
}
field.set(entity, Integer.valueOf(str));
}
} else if (field.getType() == String.class) {
String[] strs = str.split("\\.");
if (strs.length > 1 && "0".equals(strs[1])) {
str = strs[0];
}
field.set(entity, str);
} else if (field.getType() == BigDecimal.class) {
BigDecimal amount = new BigDecimal(str);
field.set(entity, amount);
} else if (field.getType() == Date.class) {
if (str.length() > 8) {
str = str.replace("-", "").replace("/", "");
if (str.length() > 8) {
str = str.substring(0, 8);
}
}
field.set(entity, new SimpleDateFormat("yyyyMMdd").parse(str));
} else {
log.info("field.getType()=" + field.getType() + "");
field.set(entity, str);
}
}
break;
}
// 字符串
case STRING: {
String str = cell.toString();
if (field.getType() == Date.class) {
Date date = new SimpleDateFormat("yyyyMMdd").parse(str);
field.set(entity, date);
} else if (field.getType() == Integer.class) {
if (StringUtils.isNotEmpty(str)) {
String[] strs = str.split("\\.");
if (strs.length > 1 && "0".equals(strs[1])) {
str = strs[0];
}
field.set(entity, Integer.valueOf(str));
}
} else if (field.getType() == String.class) {
String[] strs = str.split("\\.");
if (strs.length > 1 && "0".equals(strs[1])) {
str = strs[0];
}
field.set(entity, str);
} else if (field.getType() == BigDecimal.class) {
BigDecimal amount = new BigDecimal(str);
field.set(entity, amount);
} else {
field.set(entity, str);
}
break;
}
default: {
break;
}
}
}
}
int firstCellNum = row.getFirstCellNum(); //第一个列位置
int lastCellNum = row.getLastCellNum(); //最后一列位置
//所有列都为空
if (nullCellNum == (lastCellNum - firstCellNum)) {
continue;
}
list.add(entity);
} catch (Exception e) {
log.error("解析excel异常", e);
return null;
}
}
return list;
}
}
总结
.========================努力干吧!菜鸟。