poi 对日期cell的验证转换

Excel 文件中有的人在日期的单元格里面输入字符串,有的人输入日期类型的数据,这就比较讨厌

所以读取日期的单元格要小心

下面是一个方法,验证上传excel文件时输入的日期是否正确的。

public static boolean checkFilebyDate(File file,Date fromDate,Date toDate){
		SimpleDateFormat  parseTime = new SimpleDateFormat("dd/MM/yyyy");
		FileInputStream in = null;
		try {
			in = new FileInputStream(file);
			HSSFWorkbook workbook = new HSSFWorkbook(in); 
			HSSFSheet sheet = workbook.getSheetAt(0);   
			int lrnum = sheet.getLastRowNum();  
			Date excelFromDate = null;
			Date excelToDate = null;
			HSSFCell cellTo = sheet.getRow(1).getCell(1);
			HSSFCell cellFrom = sheet.getRow(lrnum-1).getCell(1);
			if(cellTo.getCellType() == HSSFCell.CELL_TYPE_STRING){
				String from = cellFrom.getStringCellValue();
				String to = cellTo.getStringCellValue();
				excelFromDate = parseTime.parse(from);
				excelToDate = parseTime.parse(to);
			}else if(cellTo.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){			
				double from = cellFrom.getNumericCellValue();
				double to = cellTo.getNumericCellValue();
				//boolean b = HSSFDateUtil.isCellDateFormatted(cellTo);
				excelFromDate = HSSFDateUtil.getJavaDate(from);
				excelToDate = HSSFDateUtil.getJavaDate(to);
			}else{
				return false;
			}
			
			in.close();
			if(excelFromDate.getTime() < fromDate.getTime()){
				return false;
			}else if(excelToDate.getTime() > toDate.getTime()){
				return false;
			}else{
				return true;
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (ParseException e) {
			e.printStackTrace();
			return false;
		}finally{
			System.out.print("checkFilebyDate");
		}			
	}
 

 

你可能感兴趣的:(Excel)