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;
    }

猜你喜欢

转载自blog.csdn.net/qq_35029061/article/details/82401735