解析Excel工具類

pom依賴:

        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.15</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>

工具類:

package com.swj.service;

import com.swj.basic.exception.ServiceException;
import com.swj.basic.helper.StringHelper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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 org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 解析Excel工具類
 *
 * @author chenlg
 * @since 2018/10/11
 **/
public class ExcelHelper {

    /**
     * 獲取某一行的數據
     * @author chenlg
     * @since 2018/10/11
     * @param excel 文件
     * @param rowNum 列號
     * @return java.util.List<java.lang.String>
     */
    public static List<String> getRow(File excel, Integer rowNum) {
        if (excel == null || rowNum < 0) {
            throw new ServiceException("Invalid arguments at ExcelHelper.getRow");
        }
        try {
            Workbook wb = validateFile(excel);
            //開始解析
            List<String> result = null;
            Sheet sheet = wb.getSheetAt(0);
            //開始解析
                Row row = sheet.getRow(rowNum);
                if (row != null) {
                    int firstCellIndex = row.getFirstCellNum();
                    int lastCellIndex = row.getLastCellNum();
                    for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {
                        Cell cell = row.getCell(cIndex);
                        result.add(cell == null ? "" : cell.toString());
                    }
                }
            return result;
        } catch (Exception e) {
            throw new ServiceException("解析excel文件失敗");
        }
    }

    /**
     * 根據標題獲取某一列的數據
     * @author chenlg
     * @since 2018/10/11
     * @param excel 文件
     * @param title 列標題
     * @return java.util.List<java.lang.String>
     */
    public static List<String> getColumnByTitle(File excel, String title) {
        Integer colNum = getColumnNum(excel, title);
        if (colNum!=null && colNum>=0){
            return getColumn(excel,colNum);
        }else{
            return new ArrayList<>();
        }
    }

    /**
     * 獲取某一列的數據
     * @author chenlg
     * @since 2018/10/11
     * @param excel 文件
     * @param colNum 列號
     * @return java.util.List<java.lang.String>
     */
    public static List<String> getColumn(File excel, Integer colNum) {
        if (excel == null || colNum < 0) {
            throw new ServiceException("Invalid arguments at ExcelHelper.getColumn");
        }
        try {
            Workbook wb = validateFile(excel);
            //開始解析
            List<String> result = new ArrayList<>();
            Sheet sheet = wb.getSheetAt(0);
            int firstRowIndex = sheet.getFirstRowNum();
            int lastRowIndex = sheet.getLastRowNum();
            for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {
                Row row = sheet.getRow(rIndex);
                if (row != null) {
                    Cell cell = row.getCell(colNum);
                    result.add(cell == null ? "" : cell.toString());
                }
            }
            return result;
        } catch (Exception e) {
            throw new ServiceException("解析excel文件失敗");
        }
    }

    /**
     * 根據列名獲取列號
     *
     * @author chenlg
     * @since 2018/10/11
     * @param colName 列名
     * @param excel   文件
     * @return java.lang.Integer
     */
    public static Integer getColumnNum(File excel, String colName) {
        if (excel == null || StringHelper.isNullOrEmpty(colName)) {
            throw new ServiceException("Invalid arguments at ExcelHelper.getColumnNum");
        }
        Workbook wb = validateFile(excel);
        //開始解析
        Sheet sheet = wb.getSheetAt(0);
        Row title = sheet.getRow(0);
        if (title == null) {
            throw new ServiceException("excel文件標題行爲空");
        }
        int firstCellIndex = title.getFirstCellNum();
        int lastCellIndex = title.getLastCellNum();
        for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {
            Cell cell = title.getCell(cIndex);
            if (cell != null && cell.toString().equals(colName)) {
                return cell.getColumnIndex();
            }
        }
        return -1;
    }

    private static Workbook validateFile(File excel) {
        try {
            //判斷文件是否存在
            String[] split = excel.getName().split("\\.");
            Workbook wb;
            //根據文件後綴(xls/xlsx)進行判斷
            if ("xls".equals(split[1])) {
                FileInputStream fis = new FileInputStream(excel);
                wb = new HSSFWorkbook(fis);
            } else if ("xlsx".equals(split[1])) {
                wb = new XSSFWorkbook(excel);
            } else {
                throw new ServiceException("文件類型錯誤!");
            }
            return wb;
        } catch (Exception e) {
            throw new ServiceException("解析excel文件失敗");
        }
    }

}

 

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