讀取Excel數據入庫(mysql)

思路:

使用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);

注意:日期類型都要先獲取純數值,然後再進行轉換.

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章