在java读取excel获取数据存入数据库时,经常会遇到多种日期类型和时间类型混用的情况
比如这样,一边是纯日期,一边是“年月日 时分秒”形式,
很多时候我们需要直接根据内容来区分二者,从而将取到的时间值转换成与excel展现一致的数字,然
private static Object getCellValue(Cell cell, Workbook workbook) {Object value = "";if (cell != null) {try {// 判断类型switch (cell.getCellType()) {//字符串case Cell.CELL_TYPE_STRING:value = cell.getStringCellValue();break;case Cell.CELL_TYPE_NUMERIC:if (HSSFDateUtil.isCellDateFormatted(cell)) {// 日期类型// 短日期转化为字符串Date date = cell.getDateCellValue();if (date != null) {// 标准0点 1970/01/01 08:00:00if (date.getTime() % 86400000 == 16 * 3600 * 1000 && cell.getCellStyle().getDataFormat() == 14) {value = new SimpleDateFormat("yyyy-MM-dd").format(date);} else {value = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);}}} else {// 数值//System.out.println("Value:"+cell.getNumericCellValue());String numberStr = new HSSFDataFormatter().formatCellValue(cell);// 货币格式,如:1,200.00if (numberStr.contains(",")) {numberStr = numberStr.replace(",", "");}if (numberStr.contains("E")) { // 科学计算法numberStr = new DecimalFormat("0").format(cell.getNumericCellValue()); //4.89481368464913E14还原为长整数value = Long.parseLong(numberStr);} else {if (numberStr.contains(".")) { // 小数value = Double.parseDouble(numberStr);} else { // 转换为整数value = Long.parseLong(numberStr);}}}break;case Cell.CELL_TYPE_FORMULA:// 导入时如果为公式生成的数据则无值break;case Cell.CELL_TYPE_BLANK://空break;case Cell.CELL_TYPE_BOOLEAN:value = (cell.getBooleanCellValue() == true ? "Y" : "N");break;}} catch (Exception e) {System.out.println("读取XLS异常,异常单元格:" + cell);throw e;}}return value;}
后就有了下面的办法