萬能poi導入功能模板


同時支持2007版本和2003版本,空行過濾,純數字類型數據格式處理,日期格式處理等

package com.yss.db.util;

import com.yss.base.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author maokaixuan
 * @Description //讀取excel數據並導入到數據庫
 * @Date 20:13 2019/2/15
 * @Param
 * @return
 **/
@Slf4j
public class ImportExcel {
    /**
     * @return java.util.Map
     * @Author maokaixuan
     * @Description //讀取Excel數據內容
     * @Date 13:24 2019/2/16
     * @Param [is]
     **/
    public Map<Integer, String[]> readExcelContent(String path) throws BaseException {
        Map<Integer, String[]> content = new HashMap<>();
        Workbook wb = null;
        try {
            wb = WorkbookFactory.create(new File(path));
        } catch (IOException e) {
            log.info("文件類型不匹配,請重新選擇!", e);
            throw new BaseException("文件類型不匹配,請重新選擇!", e);
        } catch (InvalidFormatException e) {
            log.info("文件類型不匹配,請重新選擇!", e);
            throw new BaseException("文件類型不匹配,請重新選擇!", e);
        }

        Sheet sheet = wb.getSheetAt(0);
        // 得到總行數
        int rowNum = getExcelRealRow(sheet);
        if (rowNum < 1) {
            throw new BaseException("導入文件數據為空!");
        }
        //由於第0行是表頭在這里表數據索引從1開始
        Row row = sheet.getRow(1);
        int colNum = row.getPhysicalNumberOfCells();
        // 正文內容應該從第二行開始,第一行為表頭的標題
        for (int i = 1; i <= rowNum; i++) {
            String[] strValue = new String[colNum];
            row = sheet.getRow(i);
            int j = 0;
            while (j < colNum) {
                strValue[j] = getCellFormatValue(row.getCell((short) j)).trim();
                j++;
            }
            content.put(i, strValue);
        }
        return content;
    }

    // 獲取Excel表的真實行數
    int getExcelRealRow(Sheet sheet) {
        boolean flag = false;
        for (int i = 1; i <= sheet.getLastRowNum(); ) {
            Row r = sheet.getRow(i);
            if (r == null) {
                // 如果是空行(即沒有任何數據、格式),直接把它以下的數據往上移動
                sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
                continue;
            }
            flag = false;
            for (Cell c : r) {
                if (c.getCellType() != Cell.CELL_TYPE_BLANK) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                i++;
                continue;
            } else {
                // 如果是空白行(即可能沒有數據,但是有一定格式)
                if (i == sheet.getLastRowNum())// 如果到了最后一行,直接將那一行remove掉
                    sheet.removeRow(r);
                else//如果還沒到最后一行,則數據往上移一行
                    sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
            }
        }
        return sheet.getLastRowNum();
    }

    /**
     * @return java.lang.String
     * @Author maokaixuan
     * @Description //根據HSSFCell類型設置數據
     * @Date 17:51 2019/3/3
     * @Param [cell]
     **/
    private String getCellFormatValue(Cell cell) {
        String cellvalue = "";
        if (cell != null) {
            // 判斷當前Cell的Type
            switch (cell.getCellType()) {
                // 如果當前Cell的Type為NUMERIC
                case HSSFCell.CELL_TYPE_NUMERIC:
                case HSSFCell.CELL_TYPE_FORMULA: {
                    // 判斷當前的cell是否為Date
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        Date date = cell.getDateCellValue();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        cellvalue = sdf.format(date);
                    }
                    // 如果是純數字
                    else {
                        // 取得當前Cell的數值
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cellvalue = String.valueOf(cell.getStringCellValue().trim());
                    }
                    break;
                }
                // 如果當前Cell的Type為STRIN
                case HSSFCell.CELL_TYPE_STRING:
                    // 取得當前的Cell字符串
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                // 默認的Cell值
                default:
                    cellvalue = " ";
            }
        } else {
            cellvalue = "";
        }
        return cellvalue;

    }

}

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM