思路:
使用idea创建spring boot项目集成springboot -data-jpa做数据存储,
导入maven:
<!--引入poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!--引入poi 读取 xlsx-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
第一步:创建实体
package com.example.readexcel.entity;
import org.springframework.stereotype.Component;
import javax.persistence.*;
/**
* @author:
* @date: 2019/11/19
* @description:
**/
@Component
@Entity
@Table(name = "MerchantInfo")
public class MerchantInfo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
//@Basic(optional = false)
@Column(name = "id")
private int id;
@Column(name = "merchantName")
private String merchantName;
@Column(name = "merchantNumber")
private String merchantNumber;
@Column(name = "settleStartDate")
private String settleStartDate;
@Column(name = "settleStopDate")
private String settleStopDate;
@Column(name = "businessType")
private String businessType;
@Override
public String toString() {
return "MerchantInfo{" +
"id=" + id +
", merchantName='" + merchantName + '\'' +
", merchantNumber='" + merchantNumber + '\'' +
", settleStartDate='" + settleStartDate + '\'' +
", settleStopDate='" + settleStopDate + '\'' +
", businessType='" + businessType + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMerchantName() {
return merchantName;
}
public void setMerchantName(String merchantName) {
this.merchantName = merchantName;
}
public String getMerchantNumber() {
return merchantNumber;
}
public void setMerchantNumber(String merchantNumber) {
this.merchantNumber = merchantNumber;
}
public String getSettleStartDate() {
return settleStartDate;
}
public void setSettleStartDate(String settleStartDate) {
this.settleStartDate = settleStartDate;
}
public String getSettleStopDate() {
return settleStopDate;
}
public void setSettleStopDate(String settleStopDate) {
this.settleStopDate = settleStopDate;
}
public String getBusinessType() {
return businessType;
}
public void setBusinessType(String businessType) {
this.businessType = businessType;
}
}
第二步:读取Excel文档并判断文件类型
//读取Excel文件
File excel = new File(ExcelPath);
//判断文件是否存在
if (excel.isFile() && excel.exists()) {
int pos = excel.getName().lastIndexOf(".");
String[] split = excel.getName().substring(pos).split("\\."); //.是特殊字符,需要转义!!!!
Workbook workbook=null;
//根据文件后缀(xls/xlsx)进行判断
if("xls".equals(split[1])){
FileInputStream fis = new FileInputStream(excel); //文件流对象
workbook = new HSSFWorkbook(fis);
}else if("xlsx".equals(split[1])){
FileInputStream fis = new FileInputStream(excel);
workbook = new XSSFWorkbook(fis);
}else {
System.out.println("文件类型错误!");
return;
}
第三步:解析Excel文档
//开始解析
Sheet sheet = workbook.getSheetAt(0); //读取sheet 0
int firstRowIndex = sheet.getFirstRowNum()+1; //第一行是列名,所以不读 从第二行开始读
int lastRowIndex = sheet.getLastRowNum(); //最后一排
System.out.println("firstRowIndex: "+firstRowIndex);
System.out.println("lastRowIndex: "+lastRowIndex);
for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) { //遍历行
//初始化实体MerchantInfo
MerchantInfo merchantInfo=new MerchantInfo();
System.out.println("rIndex: " + rIndex);
Row row = sheet.getRow(rIndex);
if (row != null&& rIndex<3) {
int firstColumnIndex = row.getFirstCellNum();
int lastColumnIndex = row.getLastCellNum();
//ExcelInfo excelInfo=new ExcelInfo();
for(int cIndex = firstColumnIndex; cIndex < lastColumnIndex; cIndex++) { //遍历列
Cell cell = row.getCell(cIndex);
if (cell != null&&!"".equals(cell.toString().trim())&&rIndex==1) {
// System.out.println("cIndex:"+cIndex);
// System.out.println(cell.toString());
String pattern = "((?![商户名称:]).)*公司";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(cell.toString());
if (m.find()) {
merchantInfo.setMerchantName(m.group());
}
String pattern1 = "((?![商户号:]).\\d+)";
Pattern p1 = Pattern.compile(pattern1);
Matcher m1 = p1.matcher(cell.toString());
if (m1.find()) {
merchantInfo.setMerchantNumber( m1.group());
}
// System.out.println("MerchantNumber:"+merchantInfo.getMerchantName());
// System.out.println("MerchantNumber:"+merchantInfo.getMerchantNumber());
}else if(cell != null&&!"".equals(cell.toString().trim())&&rIndex==2){
// System.out.println("cIndex:"+cIndex);
// System.out.println(cell.toString().replaceAll(" ",""));
String pattern = "清算日期从:\\d+";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(cell.toString().replaceAll(" ",""));
if (m.find()) {
merchantInfo.setSettleStartDate(m.group().replaceAll("\\D+:",""));
}
String pattern1 = "到:\\d+";
Pattern p1 = Pattern.compile(pattern1);
Matcher m1 = p1.matcher(cell.toString().replaceAll("",""));
if (m1.find()) {
merchantInfo.setSettleStopDate(m1.group().replaceAll("\\D+:",""));
}
String pattern2 = "((?![业务类型:]).)*$";
Pattern p2 = Pattern.compile(pattern2);
Matcher m2 = p2.matcher(cell.toString().replaceAll(" ",""));
if (m2.find()) {
merchantInfo.setBusinessType(m2.group());
}
// System.out.println("MerchantNumber:"+merchantInfo.getSettleStartDate());
// System.out.println("MerchantNumber:"+merchantInfo.getSettleStopDate());
// System.out.println("MerchantNumber:"+merchantInfo.getBusinessType());
}
}
}
if(merchantInfo!=null){
try {
merchantInfoRepository.save(merchantInfo);
}catch(Exception e){
e.printStackTrace();
}
}
}
Excel取值的一些坑:
1、自定义日期取值问题:
明明是 值为“21:11:37” 解析string存储却是“10-十一月-2019”,这个是因为格式的问题,日期一般取出来的是double类型,
所以我们需要获取纯数值格式:getNumericCellValue() 直接获取数据再来进行格式转换
double value=cell.getNumericCellValue(); //获取源数值
//再来解析格式
SimpleDateFormat sdf = null;
Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
sdf = new SimpleDateFormat("yyyy-MM-dd");//or sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dates = sdf.format(date);
//存入实体
excelInfo.setTransactionDate(dates);
注意:日期类型都要先获取纯数值,然后再进行转换.