1. 程式人生 > >excel poi 匯入時日期轉為數字如何處理

excel poi 匯入時日期轉為數字如何處理

匯入日期的時候,轉為數字是因為讀取excel的是文字型別,通過getCellValue()獲取的是字串,要用getDateCellValue()獲取數值型別的資料

   //定義一個儲存所有欄位的list集合
	HashMap<Integer,String[]> columnValueList = new HashMap<Integer,String[]>(); 
     String[] columnValue = new String[3];
	columnValue[0]=fieldName;
	columnValue[2]=fieldDataType;
	columnValueList.put(fieldOrder-1, columnValue);           
 //迴圈每一個單元格(從這裡開始查詢特定欄位是否入庫   把id都查詢出來)
					for (int cycleInt=templateStartCol;cycleInt<=templateEndCol;cycleInt++ ) {
						 Cell cell = row.getCell(cycleInt);   
						 Object value = getCellValue(cell);
						 String[] columnValue = columnValueList.get(cycleInt);
          if ("DATE".equalsIgnoreCase(columnValue[0])) {
			 String StrVal = value.toString().trim();
			  try {
			 int cellType = cell.getCellType();
			 if(cellType==1) {
			 Date d1 = new SimpleDateFormat("yyyy年MM月dd日").parse(StrVal);
			 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			 String time = format.format(d1);
			 value = time;
			 }else if(cellType==0){
				 Date date = cell.getDateCellValue();
				 value = DateFormatUtils.format(date, "yyyy-MM-dd");
			  }else{
                             value="";
                         }
						} catch (ParseException e) {
					// TODO Auto-generated catch block
						e.printStackTrace();
						} 
					 } 
}

excel poi 獲取cell的值

/**
	 * 獲得cell的數值
	 * @param cell
	 * @return
	 */
	public static Object getCellValue(Cell cell) {
		if(cell==null){
			return "";
		}
		Object result = null;
		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_NUMERIC:
			  if(DateUtil.isCellDateFormatted(cell)){  
			       //如果是date型別則 ,獲取該cell的date值  
				   //result = DateUtil.getJavaDate(cell.getNumericCellValue());  
				   result = DateFormatUtils.format(cell.getDateCellValue(), "yyyy/MM/dd"); 
			  }else{ 
				  // 純數字  
				  //result =new BigDecimal( String.valueOf(cell.getNumericCellValue())).toString();  
				  result =  BigDecimal.valueOf(cell.getNumericCellValue()).stripTrailingZeros().toPlainString();
			  }  
			break;
	        case Cell.CELL_TYPE_STRING :
	            result = cell.getRichStringCellValue().getString().trim();
	            break;
	        case Cell.CELL_TYPE_FORMULA :
	           /* result = cell.getCellFormula(); 使用下面,直接獲取值*/ 
	        	DecimalFormat df = new DecimalFormat("#.0000");
	        	result = df.format(cell.getNumericCellValue());
	            break;
	        case Cell.CELL_TYPE_BOOLEAN :
	            result = cell.getBooleanCellValue();
	            break;
	        case Cell.CELL_TYPE_ERROR :
	            result = cell.getErrorCellValue();
	            break;
	        case Cell.CELL_TYPE_BLANK :
	            result = "";
	            break;
	    }
		return result;
    }