欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

poi 对日期cell的验证转换

程序员文章站 2022-03-11 12:45:40
...

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