java cell 日期_Java如何验证EXCEL中数据是否是时间日期格式及其正确性

public String compareExcelValue(Sheet sheet) {

int totalRows = sheet.getPhysicalNumberOfRows();// 得到Excel的行数

int totalCells = 0;

if (totalRows >= 1 && sheet.getRow(0) != null) {

// 得到Excel的列数(前提是有行数)

totalCells = sheet.getRow(0).getPhysicalNumberOfCells();

} else {

return "上传的Excel没有数据!";

}

SimpleDateFormat forma1 = new SimpleDateFormat("yyyy/MM/dd");

SimpleDateFormat forma2 = new SimpleDateFormat("yyyy.MM.dd");

SimpleDateFormat forma3 = new SimpleDateFormat("yyyy-MM-dd");

// 设置lenient为false.

// 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01

forma1.setLenient(false);

forma2.setLenient(false);

forma3.setLenient(false);

for (int c = 0; c < totalCells; c++) {

// 循环遍历每一列,获取第一行标题行内容

Cell cell = sheet.getRow(0).getCell(c);

// 判断标题内容是否是日期时间

if (cell.getStringCellValue().indexOf("日期") != -1 || cell.getStringCellValue().indexOf("时间") != -1) {

for (int r = 1; r < totalRows; r++) {

// 循环获取这一列的每一行

String formatTime = getValue(sheet.getRow(r).getCell(c));

try {

if (formatTime.indexOf("/") != -1) {

forma1.parse(formatTime);

} else if (formatTime.indexOf(".") != -1) {

forma2.parse(formatTime);

} else if (formatTime.indexOf("-") != -1) {

forma3.parse(formatTime);

} else {

return "Excel第" + (r + 1) + "行第" + c + "列时间格式有误!";

}

} catch (ParseException e) {

// 如果throw java.text.ParseException

// 或者NullPointerException,就说明格式不对

return "Excel第" + (r + 1) + "行第" + c + "列时间格式有误!";

}

}

}

}

return "true";

}

public String getValue(Cell cell) {

String cellValue = "";

switch (cell.getCellType()) {

case Cell.CELL_TYPE_STRING:

cellValue = cell.getStringCellValue();

break;

case Cell.CELL_TYPE_BOOLEAN:

cellValue = String.valueOf(cell.getBooleanCellValue());

break;

case Cell.CELL_TYPE_NUMERIC:

if (DateUtil.isCellDateFormatted(cell)) {

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

cellValue = sdf.format(cell.getDateCellValue());

} else {

DataFormatter dataFormatter = new DataFormatter();

cellValue = dataFormatter.formatCellValue(cell);

}

break;

default:

cellValue = "";

break;

}

return cellValue;

}


版权声明:本文为weixin_33735281原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。