JAVA导入Excel后,时间变为数字,转日期方法
一、先说一下通常的Excel 导入:
Excel 导入后,获取时间数据: <在这里 format 就是时间格式>
private static String getCellStringVal(Cell cell, String format) {
CellType cellType = cell.getCellTypeEnum();
switch (cellType) {
case NUMERIC:
String value;
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
value = TimeTool.dateToFormatTime(date, format);
} else {
double dValue = cell.getNumericCellValue();
DecimalFormat df = new DecimalFormat("0");
value = df.format(dValue);
}
return value;
case STRING:
return cell.getStringCellValue();
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
case FORMULA:
return cell.getCellFormula();
case BLANK:
return "";
case ERROR:
return String.valueOf(cell.getErrorCellValue());
default:
return "";
}
}
二、如果说我们使用的不是poi,或者其他。导入后日期为数字:
getTime();// ditNumber = 43607.4166666667
这里,我们需要保存时间戳到数据库,所以这里做了判断,且返回String。
Date、Timestamp已有,需要直接返回即可。
//Mysql支持的时间戳限制
static long minTime = Timestamp.valueOf("1970-01-01 09:00:00").getTime();
static long maxTime = Timestamp.valueOf("2038-01-19 11:00:00").getTime();
static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//判断 并转换时间格式 ditNumber = 43607.4166666667
public static String getTime(String ditNumber) {
//如果是数字 小于0则 返回
BigDecimal bd = new BigDecimal(ditNumber);
int days = bd.intValue();//天数
int mills = (int) Math.round(bd.subtract(new BigDecimal(days)).doubleValue() * 24 * 3600);
//获取时间
Calendar c = Calendar.getInstance();
c.set(1900, 0, 1);
c.add(Calendar.DATE, days - 2);
int hour = mills / 3600;
int minute = (mills - hour * 3600) / 60;
int second = mills - hour * 3600 - minute * 60;
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, second);
Date d = c.getTime();//Date
return DateUtil.formatDateTime(d);
}
//校验是否数据含小数点
private static boolean isNotNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]+\\.*[0-9]*");
Matcher isNum = pattern.matcher(str);
if(!isNum.matches()){
return false;
}
return true;
}
继上,给大家提供校验日期格式的方法:
static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//传入String,返回boolean
public static boolean checkDate(String date) {
if (date != null && date.isEmpty()) {
try {
//禁止SimpleDateFormat的自动计算功能,严格解析日期
dateFormat.setLenient(false);
dateFormat.parse(date);
} catch (Exception e) {
System.out.println("传入日期错误" + date);
return false;
}
return true;
}
return false;
}
//传入java.util.Date,返回boolean
public static boolean checkDate(Date date) {
if (date != null) {
try {
//禁止SimpleDateFormat的自动计算功能,严格解析日期
dateFormat.setLenient(false);
dateFormat.format(date);
} catch (Exception e) {
System.out.println("传入日期错误" + date);
return false;
}
return true;
}
return false;
}
手动操作导入
public void updateOrderExpress(MultipartFile file) throws Exception {
Workbook wb = new XSSFWorkbook(file.getInputStream());
//根据页面index 获取sheet页
Sheet sheet = wb.getSheetAt(0);
Row row = null;
int rowNum = 0;
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
rowNum+=1;
String errorMes = "";
//获取每一行数据
row = rowIterator.next();
if (rowNum == 1) {
continue;
}
if (ObjectUtil.isEmpty(row)) {
continue;
}
for (int j = 1; j <= 3; j++) {
if (ObjectUtil.isNotEmpty(row.getCell(j))) {
row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
}
}
String orderSn = ObjectUtil.isNotEmpty(row.getCell(0)) ? row.getCell(0).toString() : "";
String expressCompany = ObjectUtil.isNotEmpty(row.getCell(1)) ? row.getCell(1).toString() : "";
String expressNo = ObjectUtil.isNotEmpty(row.getCell(2)) ? row.getCell(2).toString() : "";
String expressTime = ObjectUtil.isNotEmpty(row.getCell(3)) ? row.getCell(3).toString() : "";
logger.info("导入 {} 行 orderSn:{} expressCompany:{} expressNo:{} expressTime:{}", row.getRowNum(), orderSn, expressCompany, expressNo, expressTime);
if (ObjectUtil.isEmpty(orderSn)) {
errorMes = "订单号不存在 ";
}
if (ObjectUtil.isEmpty(expressCompany)) {
errorMes += "物流公司不存在 ";
}
if (ObjectUtil.isEmpty(expressNo)) {
errorMes += "物流单号不存在 ";
}
if (ObjectUtil.isNotEmpty(expressTime) && !ExportExcelUtil.isNotNumeric(expressTime)) {
expressTime = ExportExcelUtil.getTime(expressTime);
}
if (ObjectUtil.isEmpty(expressTime)) {
expressTime = cn.hutool.core.date.DateUtil.formatDateTime(new Date());
}
try{
expressTime = cn.hutool.core.date.DateUtil.formatDateTime(cn.hutool.core.date.DateUtil.parse(expressTime));
} catch (Exception e){
errorMes += "发货时间格式不正确 ";
}
UserOrderDto orderInfo = getOrderByOrderSn(orderSn);
if (ObjectUtil.isEmpty(orderInfo)) {
errorMes += "订单不存在 ";
} else {
if (!"express".equals(orderInfo.getOrderMode())){
errorMes = "订单为自取订单 ";
}
}
if (!(OrderStatusEnum.PAID.getKey().equals(orderInfo.getStatus()) || OrderStatusEnum.DELIVERY.getKey().equals(orderInfo.getStatus()))) {
errorMes += "订单状态不正确 ";
}
ExpressDto expressDto = new ExpressDto();
expressDto.setExpressCompany(expressCompany);
expressDto.setExpressTime(expressTime);
expressDto.setExpressNo(expressNo);
if (ObjectUtil.isNotEmpty(expressDto.getExpressNo())
&& ObjectUtil.isNotEmpty(expressDto.getExpressCompany())
&& ObjectUtil.isNotEmpty(expressDto.getExpressTime())
&& ObjectUtil.isNotEmpty(orderSn)
) {
OrderDto reqDto = new OrderDto();
reqDto.setId(orderInfo.getId());
reqDto.setExpressInfo(expressDto);
reqDto.setStatus(OrderStatusEnum.DELIVERED.getKey());
reqDto.setUpdateTime(new Date());
try {
// updateOrder(reqDto);
} catch (Exception e) {
logger.info("导入 {} 行 订单号:{} 保存错误信息:{}", row.getRowNum(), orderSn, e.getMessage());
throw new BusinessCheckException(orderSn + " " + e.getMessage());
}
} else {
errorMes += "订单导入失败 ";
}
if (ObjectUtil.isNotEmpty(errorMes)) {
logger.info("导入 {} 行 订单号:{} 错误信息:{}", row.getRowNum(), orderSn, errorMes);
throw new BusinessCheckException(orderSn + " " + errorMes);
}
}
}