1. 程式人生 > >java使用poi讀取excel表格資料工具類

java使用poi讀取excel表格資料工具類

package com.eyric.excel;

import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import com.eyric.excel.dto.ExcelData;
import com.eyric.excel.dto.ExcelLineData;
import com.eyric.excel.dto.ExcelSheetData;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;

/**
 * 讀取Excel資料工具類
 *
 * @time 2017-06-03
 */
public class ExcelReader {
    private static POIFSFileSystem fs;
    private static HSSFWorkbook wb;
    private static HSSFSheet sheet;
    private static HSSFRow row;

    /**
     * 獲取多個sheetExcel表格資料
     *
     * @param fileName Excel 資料表格
     * @return
     */
    public ExcelData readMultiSheetExcel(String fileName) {
        InputStream is = null;
        File file = new File(fileName);
        try {
            is = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        ExcelData excelData = new ExcelData();
        try {
            fs = new POIFSFileSystem(is);
            wb = new HSSFWorkbook(fs);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Integer sheetNum = wb.getNumberOfSheets();
        excelData.setSheetSum(sheetNum);
        excelData.setFileName(file.getName());

        //迴圈獲取所有sheet資料
        List<ExcelSheetData> sheetDatas = new ArrayList<>();
        for (int i = 0; i < sheetNum; i++) {
            ExcelSheetData sheetData = new ExcelSheetData();
            sheet = wb.getSheetAt(i);
            sheetData.setLineSum(sheet.getPhysicalNumberOfRows());
            sheetData.setSheetName(sheet.getSheetName());

            List<ExcelLineData> lineDatas = readExcelContentBySheet(sheet);
            sheetData.setLineData(lineDatas);
            sheetDatas.add(sheetData);
        }
        excelData.setSheetData(sheetDatas);
        return excelData;
    }


    private List<ExcelLineData> readExcelContentBySheet(HSSFSheet sheet) {
        List<ExcelLineData> lineDatas = new ArrayList<>();
        // 得到總行數
        int rowNum = sheet.getLastRowNum();
        for (int i = 0; i <= rowNum; i++) {
            int j = 0;
            row = sheet.getRow(i);
            if (Objects.isNull(row)) {
                continue;
            }

            int colNum = row.getPhysicalNumberOfCells();
            ExcelLineData lineData = new ExcelLineData();
            List<String> colData = new ArrayList<>();
            lineData.setColSum(colNum);
            while (j < colNum) {
                String value = getCellValue(row.getCell((short) j)).trim();
                colData.add(value);
                j++;
            }
            lineData.setColData(colData);
            lineDatas.add(lineData);
        }

        return lineDatas;
    }


    /**
     * 獲取單元格資料
     *
     * @param cell Excel單元格
     * @return String 單元格資料內容
     */
    private String getCellValue(HSSFCell cell) {
        if (Objects.isNull(cell)) {
            return "";
        }

        String value = "";
        switch (cell.getCellType()) {
            case HSSFCell.CELL_TYPE_NUMERIC: // 數字
                //如果為時間格式的內容
                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    //注:format格式 yyyy-MM-dd hh:mm:ss 中小時為12小時制,若要24小時制,則把小h變為H即可,yyyy-MM-dd HH:mm:ss
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
                    break;
                } else {
                    value = new DecimalFormat("0").format(cell.getNumericCellValue());
                }
                break;
            case HSSFCell.CELL_TYPE_STRING: // 字串
                value = cell.getStringCellValue();
                break;
            case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
                value = cell.getBooleanCellValue() + "";
                break;
            case HSSFCell.CELL_TYPE_FORMULA: // 公式
                value = cell.getCellFormula() + "";
                break;
            case HSSFCell.CELL_TYPE_BLANK: // 空值
                value = "";
                break;
            case HSSFCell.CELL_TYPE_ERROR: // 故障
                value = "非法字元";
                break;
            default:
                value = "未知型別";
                break;
        }
        return value;
    }

    public static void main(String[] args) {
        ExcelReader excelReader = new ExcelReader();
        ExcelData excelData = excelReader.readMultiSheetExcel("D:\\P38.xls");
        System.out.println(excelData.toString());
      
    }

}
package com.eyric.excel.dto;

import lombok.Data;

import java.util.List;

/**
 * @Auther: lwt
 * @Date: 2018/7/31 16:02
 * @Since: 0.1.0
 * @Description:
 */
@Data
public class ExcelData {
    private int sheetSum;
    private String fileName;
    private List<ExcelSheetData> sheetData;
}
package com.eyric.excel.dto;

import lombok.Data;

import java.util.List;

/**
 * @Auther: lwt
 * @Date: 2018/7/31 15:52
 * @Since: 0.1.0
 * @Description:
 */
@Data
public class ExcelSheetData {
    /**
     * 工作簿名稱
     */
    private String sheetName;
    /**
     * 表格總行數
     */
    private int lineSum;
    /**
     * 行資料集合
     */
    private List<ExcelLineData> lineData;
}
package com.eyric.excel.dto;

import lombok.Data;

import java.util.List;

/**
 * @Auther: lwt
 * @Date: 2018/7/31 15:54
 * @Since: 0.1.0
 * @Description:
 */
@Data
public class ExcelLineData {
    /**
     * 行編號
     */
    private int lineNumber;
    /**
     * 行總列數
     */
    private int colSum;
    /**
     * 列資料集合
     */
    private List<String> colData;
}