POI解析Excel文件工具类


	/**
	 * 读取excel数据
	 */
	public static List> exportListFromExcel(File file, int sheetNum) throws IOException {  
        return exportListFromExcel(new FileInputStream(file), FilenameUtils.getExtension(file.getName()), sheetNum);  
    }  
  
    public static List> exportListFromExcel(InputStream is, String extensionName, int sheetNum) throws IOException {  
  
        Workbook workbook = null;  
  
        if (extensionName.toLowerCase().equals(XLS)) {  
            workbook = new HSSFWorkbook(is);  
        } else if (extensionName.toLowerCase().equals(XLSX)) {  
            workbook = new XSSFWorkbook(is);  
        }  
  
        return readCell(workbook, sheetNum);  
    }  
  
    public static List> readCell(Workbook workbook, int sheetNum) {  
        Sheet sheet = workbook.getSheetAt(sheetNum);  
        List> list = new ArrayList>();
        int sNum=1;
        if(sheetNum==0) { //如果是片1 
        	sNum=0;
        }else if(sheetNum==1){//如果是片2 
        	sNum=2;
        }
        for (int i=sNum; i <= sheet.getLastRowNum(); i++) {  
            Row row = sheet.getRow(i);  
            Map map = new HashMap();  
            for (Cell cell : row) {  
  
                CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());  
                String key = cellRef.formatAsString();  
  
                switch (cell.getCellType()) {  
                case Cell.CELL_TYPE_STRING:  
                    map.put(key, cell.getRichStringCellValue().getString());  
                    break;  
                case Cell.CELL_TYPE_NUMERIC:  
                    if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {  
                        map.put(key, cell.getDateCellValue());  
                    } else {
                    	DecimalFormat dfs = new DecimalFormat("0");
                        map.put(key, dfs.format(cell.getNumericCellValue()));  
                    }  
                    break;  
                case Cell.CELL_TYPE_BOOLEAN:  
                    map.put(key, cell.getBooleanCellValue());  
                    break;  
                case Cell.CELL_TYPE_FORMULA:  
                    map.put(key, cell.getCellFormula());  
                    break;  
                case Cell.CELL_TYPE_BLANK:  
                    break;  
                case Cell.CELL_TYPE_ERROR:  
                    break;  
                default:  
                    map.put(key, "");  
                }  
            }  
            list.add(map);  
        }  
        return list;  
    } 

POM文件

 


		
		
			org.apache.poi
			poi
			3.17
		
		
		
			org.apache.poi
			poi-ooxml
			3.17
		
		
		
		
			commons-io
			commons-io
			2.5
		

		
			org.apache.commons
			commons-lang3
			3.7
		

 

你可能感兴趣的:(POI)