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;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值