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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章