1. 程式人生 > >poi讀取excel(xls,xlsx)

poi讀取excel(xls,xlsx)

這是一個poi讀取excel的工具類,支援excel2003,2007以上版本

package io.utils;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liang
 * @Description: TODO(poi工具)
 * @date 2017-7-20 18:42
 */
public class PoiUtils {

    /**
     * 讀取excel
     * @param filePath
     * @return List<Map>
     * @throws Exception
     */
    public static List<Map> readExcel(String filePath) throws Exception{
        File file=new File(filePath);
        if (!file.exists()) {
            return null;
        }

        String suffix=FileUtils.getSuffix(filePath);

        if(!".xls".equals(suffix) && !".xlsx".equals(suffix)){
            return null;
        }

        //返回值列
        List<Map> reaultList=new ArrayList<Map>();
        if(".xls".equals(suffix)){
            reaultList=readExcel2003(filePath);
        }else if(".xlsx".equals(suffix)){
            reaultList=readExcel2007(filePath);
        }

        return reaultList;
    }

    /**
     * 讀取97-2003格式
     * @param filePath 檔案路徑
     * @throws java.io.IOException
     */
    public static List<Map> readExcel2003(String filePath) throws IOException{
        //返回結果集
        List<Map> valueList=new ArrayList<Map>();
        FileInputStream fis=null;
        try {
            fis=new FileInputStream(filePath);
            HSSFWorkbook wookbook = new HSSFWorkbook(fis);  // 建立對Excel工作簿檔案的引用
            HSSFSheet sheet = wookbook.getSheetAt(0);   // 在Excel文件中,第一張工作表的預設索引是0
            int rows = sheet.getPhysicalNumberOfRows(); // 獲取到Excel檔案中的所有行數
            Map<Integer,String> keys=new HashMap<Integer, String>();
            int cells=0;
            // 遍歷行(第1行  表頭) 準備Map裡的key
            HSSFRow firstRow = sheet.getRow(0);
            if (firstRow != null) {
                // 獲取到Excel檔案中的所有的列
                cells = firstRow.getPhysicalNumberOfCells();
                // 遍歷列
                for (int j = 0; j < cells; j++) {
                    // 獲取到列的值
                    try {
                        HSSFCell cell = firstRow.getCell(j);
                        String cellValue = getCellValue(cell);
                        keys.put(j,cellValue);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            // 遍歷行(從第二行開始)
            for (int i = 1; i < rows; i++) {
                // 讀取左上端單元格(從第二行開始)
                HSSFRow row = sheet.getRow(i);
                // 行不為空
                if (row != null) {
                    //準備當前行 所儲存值的map
                    Map<String, Object> val=new HashMap<String, Object>();

                    boolean isValidRow = false;

                    // 遍歷列
                    for (int j = 0; j < cells; j++) {
                        // 獲取到列的值
                        try {
                            HSSFCell cell = row.getCell(j);
                            String cellValue = getCellValue(cell);
                            val.put(keys.get(j),cellValue);
                            if(!isValidRow && cellValue!=null && cellValue.trim().length()>0){
                                isValidRow = true;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    //第I行所有的列資料讀取完畢,放入list
                    if(isValidRow){
                        valueList.add(val);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            fis.close();
        }
        return valueList;
    }
    /**
     * 讀取2007-2013格式
     * @param filePath 檔案路徑
     * @return
     * @throws java.io.IOException
     */
    public static List<Map> readExcel2007(String filePath) throws IOException{
        List<Map> valueList=new ArrayList<Map>();
        FileInputStream fis =null;
        try {
            fis =new FileInputStream(filePath);
            XSSFWorkbook xwb = new XSSFWorkbook(fis);   // 構造 XSSFWorkbook 物件,strPath 傳入檔案路徑
            XSSFSheet sheet = xwb.getSheetAt(0);            // 讀取第一章表格內容
            // 定義 row、cell
            XSSFRow row;
            // 迴圈輸出表格中的第一行內容 表頭
            Map<Integer, String> keys=new HashMap<Integer, String>();
            row = sheet.getRow(0);
            if(row !=null){
                for (int j = row.getFirstCellNum(); j <=row.getPhysicalNumberOfCells(); j++) {
                    // 通過 row.getCell(j).toString() 獲取單元格內容,
                    if(row.getCell(j)!=null){
                        if(!row.getCell(j).toString().isEmpty()){
                            keys.put(j, row.getCell(j).toString());
                        }
                    }else{
                        keys.put(j, "K-R1C"+j+"E");
                    }
                }
            }
            // 迴圈輸出表格中的從第二行開始內容
            for (int i = sheet.getFirstRowNum() + 1; i <= sheet.getPhysicalNumberOfRows(); i++) {
                row = sheet.getRow(i);
                if (row != null) {
                    boolean isValidRow = false;
                    Map<String, Object> val = new HashMap<String, Object>();
                    for (int j = row.getFirstCellNum(); j <= row.getPhysicalNumberOfCells(); j++) {
                        XSSFCell cell = row.getCell(j);
                        if (cell != null) {
                            String cellValue = getCellValue(cell);
                            val.put(keys.get(j), cellValue);
                            if(!isValidRow && cellValue!= null && cellValue.trim().length()>0){
                                isValidRow = true;
                            }
                        }
                    }

                    // 第I行所有的列資料讀取完畢,放入valuelist
                    if (isValidRow) {
                        valueList.add(val);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            fis.close();
        }

        return valueList;
    }

    private static String getCellValue(HSSFCell cell) {
        DecimalFormat df = new DecimalFormat("#");
        String cellValue=null;
        if (cell == null)
            return null;
        switch (cell.getCellType()) {
            case HSSFCell.CELL_TYPE_NUMERIC:
                if(HSSFDateUtil.isCellDateFormatted(cell)){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    cellValue=sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
                    break;
                }
                cellValue=df.format(cell.getNumericCellValue());
                break;
            case HSSFCell.CELL_TYPE_STRING:
                cellValue=String.valueOf(cell.getStringCellValue());
                break;
            case HSSFCell.CELL_TYPE_FORMULA:
                cellValue=String.valueOf(cell.getCellFormula());
                break;
            case HSSFCell.CELL_TYPE_BLANK:
                cellValue=null;
                break;
            case HSSFCell.CELL_TYPE_BOOLEAN:
                cellValue=String.valueOf(cell.getBooleanCellValue());
                break;
            case HSSFCell.CELL_TYPE_ERROR:
                cellValue=String.valueOf(cell.getErrorCellValue());
                break;
        }
        if(cellValue!=null&&cellValue.trim().length()<=0){
            cellValue=null;
        }
        return cellValue;
    }

    private static String getCellValue(XSSFCell cell) {
        DecimalFormat df = new DecimalFormat("#");
        String cellValue=null;
        if (cell == null)
            return null;
        switch (cell.getCellType()) {
            case HSSFCell.CELL_TYPE_NUMERIC:
                if(HSSFDateUtil.isCellDateFormatted(cell)){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    cellValue=sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
                    break;
                }
                cellValue=df.format(cell.getNumericCellValue());
                break;
            case HSSFCell.CELL_TYPE_STRING:
                cellValue=String.valueOf(cell.getStringCellValue());
                break;
            case HSSFCell.CELL_TYPE_FORMULA:
                cellValue=String.valueOf(cell.getCellFormula());
                break;
            case HSSFCell.CELL_TYPE_BLANK:
                cellValue=null;
                break;
            case HSSFCell.CELL_TYPE_BOOLEAN:
                cellValue=String.valueOf(cell.getBooleanCellValue());
                break;
            case HSSFCell.CELL_TYPE_ERROR:
                cellValue=String.valueOf(cell.getErrorCellValue());
                break;
        }
        if(cellValue!=null&&cellValue.trim().length()<=0){
            cellValue=null;
        }
        return cellValue;
    }

}