excel自定義表頭導入

 

我用的maven是:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.9</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.9</version>
</dependency>

 1.ExcelUtil.java工具類,其中有合併單元格的判斷,取值,單元格格式設置等

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

/**
 * Created by wyc on 2019/5/29.
 */
public class ExcelUtil {

    private static ExcelUtil instance = null;
    private SXSSFWorkbook wb = null;
    private Sheet sheet = null;
    /**
     * 單例模式獲取實例
     * @return ExcelUtil對象
     */
    public static ExcelUtil getInstance(){
        if (instance == null)
            instance = new ExcelUtil();
        return instance;
    }
    
    public ExcelUtil() {
    }
    
    public ExcelUtil(SXSSFWorkbook wb, Sheet sheet) {
        this.wb = wb;
        this.sheet = sheet;
    }
    /**
     * 獲取合併單元格的值
     * @param sheet
     * @param row
     * @param column
     * @return
     */
    public String getMergedRegionValue(Sheet sheet ,int row , int column){
        int sheetMergeCount = sheet.getNumMergedRegions();

        for(int i = 0 ; i < sheetMergeCount ; i++){
            CellRangeAddress ca = sheet.getMergedRegion(i);
            int firstColumn = ca.getFirstColumn();
            int lastColumn = ca.getLastColumn();
            int firstRow = ca.getFirstRow();
            int lastRow = ca.getLastRow();

            if(row >= firstRow && row <= lastRow){
                if(column >= firstColumn && column <= lastColumn){
                    Row fRow = sheet.getRow(firstRow);
                    Cell fCell = fRow.getCell(firstColumn);
                    return getCellValue(fCell) ;
                }
            }
        }
        return null ;
    }

 /**
     * 獲取單元格二維座標,合併單元格和非合併單元格有區分
     * @param sheet
     * @param row
     * @param column
     * @return
     */
    public int[] getMergedLatitudeArray(Sheet sheet ,int row , int column){
        int sheetMergeCount = sheet.getNumMergedRegions();
        int[] latitude = {column,column,row,row,};
        for(int i = 0 ; i < sheetMergeCount ; i++){
            CellRangeAddress ca = sheet.getMergedRegion(i);
            int firstColumn = ca.getFirstColumn();
            int lastColumn = ca.getLastColumn();
            int firstRow = ca.getFirstRow();
            int lastRow = ca.getLastRow();
            if(row >= firstRow && row <= lastRow){
                if(column >= firstColumn && column <= lastColumn){
                    int[] mergedLatitude = {firstColumn,lastColumn,firstRow,lastRow};
                    return mergedLatitude ;
                }
            }
        }
        return latitude ;
    }

    /**
     * 判斷合併了行
     * @param sheet
     * @param row
     * @param column
     * @return
     */
    public boolean isMergedRow(Sheet sheet,int row ,int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            if(row == firstRow && row == lastRow){
                if(column >= firstColumn && column <= lastColumn){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判斷指定的單元格是否是合併單元格
     * @param sheet
     * @param row 行下標
     * @param column 列下標
     * @return
     */
    public boolean isMergedRegion(Sheet sheet,int row ,int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            if(row >= firstRow && row <= lastRow){
                if(column >= firstColumn && column <= lastColumn){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判斷sheet頁中是否含有合併單元格
     * @param sheet
     * @return
     */
    public boolean hasMerged(Sheet sheet) {
        return sheet.getNumMergedRegions() > 0 ? true : false;
    }

    /**
     * 合併單元格
     * @param sheet
     * @param firstRow 開始行
     * @param lastRow 結束行
     * @param firstCol 開始列
     * @param lastCol 結束列
     */
    public void mergeRegion(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {
        sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
    }

    /**
     * 獲取單元格的值
     * @param cell
     * @return
     */
    public String getCellValue(Cell cell){

        if(cell == null) return "";

        if(cell.getCellType() == Cell.CELL_TYPE_STRING){

            return cell.getStringCellValue();

        }else if(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN){

            return String.valueOf(cell.getBooleanCellValue());

        }else if(cell.getCellType() == Cell.CELL_TYPE_FORMULA){

            return cell.getCellFormula() ;

        }else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){

            return String.valueOf(cell.getNumericCellValue());

        }
        return "";
    }
    /**
     * 從excel讀取內容
     */
    public static void readContent(String fileName)  {
        boolean isE2007 = false;    //判斷是否是excel2007格式
        if(fileName.endsWith("xlsx"))
            isE2007 = true;
        try {
            InputStream input = new FileInputStream(fileName);  //建立輸入流
            Workbook wb  = null;
            //根據文件格式(2003或者2007)來初始化
            if(isE2007)
                wb = new XSSFWorkbook(input);
            else
                wb = new HSSFWorkbook(input);
            Sheet sheet = wb.getSheetAt(0);     //獲得第一個表單
            Iterator<Row> rows = sheet.rowIterator(); //獲得第一個表單的迭代器
            while (rows.hasNext()) {
                Row row = rows.next();  //獲得行數據
                System.out.println("Row #" + row.getRowNum());  //獲得行號從0開始
                Iterator<Cell> cells = row.cellIterator();    //獲得第一行的迭代器
                while (cells.hasNext()) {
                    Cell cell = cells.next();
                    System.out.println("Cell #" + cell.getColumnIndex());
                    switch (cell.getCellType()) {   //根據cell中的類型來輸出數據
                        case HSSFCell.CELL_TYPE_NUMERIC:
                            System.out.println(cell.getNumericCellValue());
                            break;
                        case HSSFCell.CELL_TYPE_STRING:
                            System.out.println(cell.getStringCellValue());
                            break;
                        case HSSFCell.CELL_TYPE_BOOLEAN:
                            System.out.println(cell.getBooleanCellValue());
                            break;
                        case HSSFCell.CELL_TYPE_FORMULA:
                            System.out.println(cell.getCellFormula());
                            break;
                        default:
                            System.out.println("unsuported sell type======="+cell.getCellType());
                            break;
                    }
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    // 設置表頭的單元格樣式
    public CellStyle getHeadStyle() {
        // 創建單元格樣式
        CellStyle cellStyle = wb.createCellStyle();

        // 設置單元格的背景顏色爲淡藍色
        cellStyle.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
        // 設置填充字體的樣式
        cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);

        // 設置單元格居中對齊
        cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);

        // 設置單元格垂直居中對齊
        cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        // 創建單元格內容顯示不下時自動換行
        cellStyle.setWrapText(false);

        // 設置單元格字體樣式
        XSSFFont font = (XSSFFont) wb.createFont();
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);// 這是字體加粗
        font.setFontName("宋體");// 設置字體的樣式
        font.setFontHeight(14);// 設置字體的大小
        cellStyle.setFont(font);// 將字體填充到表格中去

        // 設置單元格邊框爲細線條(上下左右)
        cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);

        return cellStyle;

    }

    // 設置表體的單元格樣式
    public CellStyle getBodyStyle() {
        // 創建單元格樣式
        CellStyle cellStyle = wb.createCellStyle();
        // 設置單元格居中對齊
        cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        // 設置單元格居中對齊
        cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        // 創建單元格內容不顯示自動換行
        cellStyle.setWrapText(false);
        // 設置單元格字體樣式
        XSSFFont font = (XSSFFont) wb.createFont();
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);// 這是字體加粗
        font.setFontName("宋體");// 設置字體
        font.setFontHeight(12);// 設置字體的大小
        cellStyle.setFont(font);// 將字體添加到表格中去

        // 設置單元格邊框爲細線條
        cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);

        return cellStyle;

    }

    public Cell setHeadStyle(String[] titles) {
        Cell cell = null;
        CellStyle headStyle = getHeadStyle();
        headStyle.setWrapText(false);
        Row headRow = sheet.createRow(0);
        // 構建表頭
        for (int i = 0; i < titles.length; i++) {
            cell = headRow.createCell(i);
            cell.setCellStyle(headStyle);
            cell.setCellValue(titles[i]);
        }
        return cell;
    }

    // 設置表頭的單元格樣式
    public CellStyle getHeadStyle(SXSSFWorkbook workbook) {
        // 創建單元格樣式
        CellStyle cellStyle = workbook.createCellStyle();
        // 設置單元格的背景顏色爲淡藍色
        cellStyle.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
        // 設置填充字體的樣式
        cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        // 設置單元格居中對齊
        cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        // 設置單元格垂直居中對齊
        cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        // 創建單元格內容顯示不下時自動換行
        cellStyle.setWrapText(true);
        // 設置單元格字體樣式
        XSSFFont font = (XSSFFont) workbook.createFont();
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);// 這是字體加粗
        font.setFontName("宋體");// 設置字體的樣式
        font.setFontHeight(12);// 設置字體的大小
        cellStyle.setFont(font);// 將字體填充到表格中去
        // 設置單元格邊框爲細線條(上下左右)
        cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
        return cellStyle;

    }

    // 設置表體的單元格樣式
    public CellStyle getBodyStyle(SXSSFWorkbook workbook) {
        // 創建單元格樣式
        CellStyle cellStyle = workbook.createCellStyle();
        // 設置單元格居中對齊
        cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        // 設置單元格居中對齊
        cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        // 創建單元格內容不顯示自動換行
        cellStyle.setWrapText(true);
        // 設置單元格字體樣式
        XSSFFont font = (XSSFFont) workbook.createFont();
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);// 這是字體加粗
        font.setFontName("宋體");// 設置字體
        font.setFontHeight(10);// 設置字體的大小
        cellStyle.setFont(font);// 將字體添加到表格中去
        // 設置單元格邊框爲細線條
        cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
        return cellStyle;

    }

    public Cell setHeadStyle(String[] titles, SXSSFWorkbook workbook) {
        Cell cell = null;
        CellStyle headStyle = getHeadStyle(workbook);
        Row headRow = sheet.createRow(0);
        // 構建表頭
        for (int i = 0; i < titles.length; i++) {
            cell = headRow.createCell(i);
            cell.setCellStyle(headStyle);
            cell.setCellValue(titles[i]);
        }
        return cell;
    }

    /**
     * 列頭單元格樣式
     */
    public CellStyle getColumnTopStyle(SXSSFWorkbook workbook) {

        // 設置字體
        Font font = workbook.createFont();
        // 設置字體大小
        font.setFontHeightInPoints((short) 18);
        // 字體加粗
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 設置字體名字
        font.setFontName("Courier New");
        // 設置樣式;
        CellStyle style = workbook.createCellStyle();
        // 設置底邊框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        // 設置底邊框顏色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        // 設置左邊框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 設置左邊框顏色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        // 設置右邊框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 設置右邊框顏色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        // 設置頂邊框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 設置頂邊框顏色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        // 在樣式用應用設置的字體;
        style.setFont(font);
        // 設置自動換行;
        style.setWrapText(false);
        // 設置水平對齊的樣式爲居中對齊;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 設置垂直對齊的樣式爲居中對齊;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        return style;
    }

}

2.ExcelMergedRegionParser解析多表頭導入,以最後一行表頭爲準,根據閾值判斷數值類型,找到最後一行表頭

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.*;


public class ExcelMergedRegionParser {
    // 閾值 臨界值
    private static int THRESHOLD = 3;
    // 數據行起始位置,默認爲-1沒有符合條件的數據行
    private static int dataLineNum = -1;
    // Excel對象
    private static Workbook workbook = null;
    // sheet下標,默認爲0
    private static int sheetNum = 0;

    /**
     *
     * @param workbook Excel對象
     */
    public ExcelMergedRegionParser(Workbook workbook){
        this.workbook = workbook;
    }
    /**
     *
     * @param workbook Excel對象
     * @param sheetNum sheet下標
     */
    public ExcelMergedRegionParser(Workbook workbook, int sheetNum){
        this.workbook = workbook;
        this.sheetNum = sheetNum;
    }

    /**
     *
     * @param workbook Excel對象
     * @param sheetNum sheet下標
     * @param THRESHOLD 臨界值
     */
    public ExcelMergedRegionParser(Workbook workbook, int sheetNum, int THRESHOLD){
        this.workbook = workbook;
        this.sheetNum = sheetNum;
        this.THRESHOLD = THRESHOLD;
    }


    /**
     *
     * @return 返回解析後的EXCEL最後一行漢字標題,有序
     */
    public List<String> getHeaderList(){
        List<String> headList = new ArrayList<>();
            // 獲取sheet頁籤
            Sheet sheet = workbook.getSheetAt(sheetNum);
            // 獲取工具類實例
            ExcelUtil excelUtil = ExcelUtil.getInstance();
            // 該sheet中是否含有合併單元格
            if (excelUtil.hasMerged(sheet)){
                    int rows = sheet.getPhysicalNumberOfRows();
                    for (int i = 0;i<rows;i++){
                        int count = 0;
                        Row row = sheet.getRow(i);
                        if(row == null)
                            continue;
                       int cells = row.getPhysicalNumberOfCells();
                       for(int j = 0 ;j<cells;j++){
                            Cell cell = row.getCell(j);
                            // 如果有一列爲null,則跳過
                            if (cell == null)
                                continue;
                            // 判斷是數字類型就加1
                            if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
                                count++;
                        }
                        // 如果計數器大於閾值說明找到了第一個數據行
                        if (count >= THRESHOLD){
                            // 數據行所在位置
                            dataLineNum = i;
                            // 聲明一個有序去重set集合
                            Set<String> setList = new LinkedHashSet<>();
                            row = sheet.getRow(i-1);
                            // 註釋的代碼,是爲了防止閾值爲0時報NULLpoint異常
                            if (row == null)
                                continue;
                            cells = row.getPhysicalNumberOfCells();
                            for(int j = 0 ;j<cells;j++){
                                Cell cell = row.getCell(j);
                                // 判斷如果有空就跳過,這裏加1是爲了彌補損失
                                if (cell == null){
                                    cells++;
                                    continue;
                                }
                                // 判斷每一個單元格是否爲合併單元格
                                boolean flag = excelUtil.isMergedRegion(sheet,i-1,j);
                                String value = "";
                                // true
                                if(flag){
                                    // 獲取合併單元格的值
                                    value = excelUtil.getMergedRegionValue(sheet,i-1,j);
                                    setList.add(value);
                                }else {
                                    value = excelUtil.getCellValue(cell);
                                    setList.add(value);
                                }
                            }
                            // 將set集合轉化爲list集合
                            headList = new ArrayList<>(setList) ;
                            break;
                        }
                    }
            }else{
                // 獲取最大物理行行數
                int rows = sheet.getPhysicalNumberOfRows();
                for (int i = 0;i<rows;i++){
                    // 數值類型計數器
                    int count = 0;
                    Row row = sheet.getRow(i);
                    if(row == null)
                        continue;
                    Iterator<Cell> cellIterator = row.cellIterator();
                    while (cellIterator.hasNext()){
                        Cell cell = cellIterator.next();
                        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
                            // 每次加1
                            count++;
                    }
                    // 如果計數器大於閾值說明找到了第一個數據行
                    if (count >= THRESHOLD){
                        // 數據行位置
                        dataLineNum = i;
                        // 獲取標題行位置
                        row = sheet.getRow(i-1);
                        // 註釋的代碼,是爲了防止閾值爲0時報NULLpoint異常
                        if (row == null)
                            continue;
                        Iterator<Cell> cellSpecIterator = row.cellIterator();
                        while (cellSpecIterator.hasNext()){
                            Cell cell = cellSpecIterator.next();
                            String value = excelUtil.getCellValue(cell);
                            headList.add(value);
                        }
                        break;
                    }
                }
            }
        return headList;
    }

    /**
     *
     * @return 數據行下標
     */
    public int getDataLineNum(){
        return this.dataLineNum;
    }

    /**
     *  得到用戶自定義表頭佈局
     * @return 返回遞歸得到的標題List
     */
    public List<CellBean> getHeaderLayout(){
        List<CellBean> headList = new ArrayList<>();
        // 獲取sheet頁籤
        Sheet sheet = workbook.getSheetAt(sheetNum);
        // 獲取最大物理行行數
        int rows = sheet.getPhysicalNumberOfRows();
        for (int i = 0;i<rows;i++){
                int count = 0;
                Row row = sheet.getRow(i);
                if(row == null)
                    continue;
                int cells = row.getPhysicalNumberOfCells();
                for(int j = 0 ;j<cells;j++){
                    Cell cell = row.getCell(j);
                    // 如果有一列爲null,則跳過
                    if (cell == null)
                        continue;
                    // 判斷是數字類型就加1
                    if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
                        count++;
                }
                // 如果計數器大於閾值說明找到了第一個數據行
                if (count >= THRESHOLD){
                    // 數據行所在位置
                    dataLineNum = i;
                    // 進行遞歸拿到標題List<CellBean>
                    headList = getCellBean(0,cells,0,0) ;
                    break;
                }
            }
        return headList;
    }

    /**
     *
     * @param firstColumn 循環開始列
     * @param lastColumn 循環結束咧
     * @param firstRow 循環開始行
     * @param lastRow 循環結束行
     * @return
     */
    public List<CellBean> getCellBean(int firstColumn, int lastColumn, int firstRow, int lastRow){
        // 遞歸結束條件 判斷到達數據行結束
        if (lastRow==dataLineNum)
            return null;
        List<CellBean> headList = new ArrayList<>();
        // 獲取sheet頁籤
        Sheet sheet = workbook.getSheetAt(sheetNum);
        // 獲取工具類實例
        ExcelUtil excelUtil = ExcelUtil.getInstance();
       //  雙重循環開始
        for (int i = firstRow;i<=lastRow;i++){
            Row row = sheet.getRow(i);
            for (int j = firstColumn;j<=lastColumn;j++){
                Cell cell = row.getCell(j);
                // 如果是合併單元格就不重複進行賦值和遞歸了,如果合併單元格的值爲空,那麼細粒度標題也不會出現在List中
                if (excelUtil.getCellValue(cell)==null||"".equals(excelUtil.getCellValue(cell)))
                    continue;
                CellBean cellBean = new CellBean();
                // 判斷該單元格是否爲合併單元格
                if (excelUtil.isMergedRegion(sheet,i,j)){
                    // 獲取合併單元格的值
                    cellBean.value = excelUtil.getMergedRegionValue(sheet,i,j);
                    // 獲取合併單元格的二維座標,同樣也支持非合併單元格
                    cellBean.latitude = excelUtil.getMergedLatitudeArray(sheet,i,j);
                    // 這裏對起始行和結束行都加1是爲了對下一行進行遞歸
                    cellBean.list = getCellBean(cellBean.latitude[0],cellBean.latitude[1],cellBean.latitude[2]+1,cellBean.latitude[3]+1);
                }else {
                    // 根據類型去單個單元格的值
                    cellBean.value = excelUtil.getCellValue(cell);
                    // 獲取非合併單元格的二維座標,同樣也支持合併單元格
                    cellBean.latitude = excelUtil.getMergedLatitudeArray(sheet,i,j);
                    // 這裏對起始行和結束行都加1是爲了對下一行進行遞歸
                    cellBean.list = getCellBean(cellBean.latitude[0],cellBean.latitude[1],cellBean.latitude[2]+1,cellBean.latitude[3]+1);
                }
                headList.add(cellBean);
            }
        }
        return headList;
    }

    /**
     * 遍歷List<CellBean>
     * @param cellBeanList
     */
    public void print(List<CellBean> cellBeanList){
        if (cellBeanList == null){
            return;
        }
        for (int i =0 ;i<cellBeanList.size();i++){
            System.out.println(cellBeanList.get(i).value);
            print(cellBeanList.get(i).list);
        }
    }

    public static void main(String[] args) {
        try {
           // File f = new File("F:\\日常薪資導入模板.xls");
            File f = new File("F:\\獎金籌劃導入模板.xls");
            FileInputStream fis = new FileInputStream(f);
            BufferedInputStream bis = new BufferedInputStream(fis);
            POIFSFileSystem fs = new POIFSFileSystem(bis);
            HSSFWorkbook workbook = null;
            workbook = new HSSFWorkbook(fs);
            ExcelMergedRegionParser excelParserController = new ExcelMergedRegionParser(workbook,0,3);
          List<String> list = excelParserController.getHeaderList();
            for(int i = 0;i<list.size();i++){
                System.out.println(list.get(i)+", ");
            }
            System.out.println(excelParserController.getDataLineNum());
            excelParserController.print(excelParserController.getHeaderLayout());

        }catch (Exception e){
            e.printStackTrace();
        }


    }
}

3.CellBean實體類 

import java.util.List;

public class CellBean {
    // 開始列,結束列,開始行,結束行
    int[] latitude;
    String value;
    List<CellBean> list;
}

 

 

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