!62 fix(excel): 修复日期格式不兼容和导入异常未上报的问题

Merge pull request !62 from wsm/fix/excel_time_import
This commit is contained in:
wsm
2026-06-30 08:25:59 +00:00
committed by Gitee
2 changed files with 34 additions and 1 deletions
@@ -234,7 +234,7 @@ public final class ExcelAnnotationUtils {
} else if (type == Date.class) {
String format = StringUtils.isNotEmpty(col.databaseFormat()) ? col.databaseFormat() : col.format();
if (StringUtils.isNotEmpty(format)) {
field.set(obj, new SimpleDateFormat(format).parse(resolved));
field.set(obj, parseDateFlexible(resolved, format));
}
} else if (type == LocalDateTime.class) {
String format = col.format();
@@ -258,6 +258,38 @@ public final class ExcelAnnotationUtils {
}
}
/**
* 弹性日期解析:依次尝试精确格式、分隔符归一化、单数字月/日格式,
* 兼容 Excel 中 "2026/6/12"、"2026-6-12"、"2026/06/12" 等常见变体。
*/
private static Date parseDateFlexible(String value, String format) throws java.text.ParseException {
// 1. 精确格式
try {
return new SimpleDateFormat(format).parse(value);
} catch (java.text.ParseException ignored) {
}
// 2. 分隔符归一化(/ → -,. → -)
String normalizedValue = value.replace('/', '-').replace('.', '-');
try {
return new SimpleDateFormat(format).parse(normalizedValue);
} catch (java.text.ParseException ignored) {
}
// 3. 单数字月/日宽松格式(MM→M, dd→d)
String relaxedFormat = format.replace("MM", "M").replace("dd", "d");
try {
return new SimpleDateFormat(relaxedFormat).parse(value);
} catch (java.text.ParseException ignored) {
}
try {
return new SimpleDateFormat(relaxedFormat).parse(normalizedValue);
} catch (java.text.ParseException ignored) {
}
throw new java.text.ParseException("Unparseable date: \"" + value + "\" with format: \"" + format + "\"", 0);
}
// ---- 私有方法 ----
private static Object getCellValue(ColumnMeta col, Object obj) {
@@ -146,6 +146,7 @@ public class ExcelImportListener<T> implements ReadListener<Map<Integer, String>
} catch (Exception e) {
skipCount[0]++;
log.error("【Excel导入】行数据转换发生 system 异常, row: {}", rowIndex, e);
handleError(rowIndex + 1, Collections.singletonList("数据转换异常: " + e.getMessage()));
}
}