fix: parse string datetime cells in external import

This commit is contained in:
2026-07-21 16:37:24 +08:00
parent 02e8b48f6d
commit 5a42a0fc5a
2 changed files with 58 additions and 8 deletions

View File

@@ -1,6 +1,7 @@
package com.ruoyi.cms.externalimport;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
@@ -11,11 +12,14 @@ import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 解析外部岗位模板。此解析器明确处理 Excel 日期单元格,替代旧导入逻辑中日期全部丢失的行为。
@@ -24,6 +28,7 @@ public class ExternalJobExcelParser {
private static final String[] REQUIRED_HEADERS = {
"Aca112", "Acb22a", "SalaryLow", "SalaryHight", "Aae397", "AAB004", "ORG", "ACE760", "Collect_time"
};
private static final Pattern TEXT_DATE_PATTERN = Pattern.compile("^\\s*(\\d{4})\\D+(\\d{1,2})\\D+(\\d{1,2}).*$");
private final DataFormatter formatter = new DataFormatter();
private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
@@ -114,11 +119,39 @@ public class ExternalJobExcelParser {
if (cell == null) {
return "";
}
if (DateUtil.isCellDateFormatted(cell)) {
if (isNumericDateCell(cell)) {
Date value = cell.getDateCellValue();
return value == null ? "" : dateFormat.format(value);
}
return formatter.formatCellValue(cell).trim();
return normalizeTextDate(formatter.formatCellValue(cell));
}
/**
* DateUtil.isCellDateFormatted 会对 STRING 单元格读取数值,导致 POI 抛出类型不匹配异常。
* 只有数值型或数值结果公式才允许进入 Excel 日期格式判断。
*/
private boolean isNumericDateCell(Cell cell) {
CellType type = cell.getCellType();
if (type == CellType.NUMERIC) {
return DateUtil.isCellDateFormatted(cell);
}
return type == CellType.FORMULA
&& cell.getCachedFormulaResultType() == CellType.NUMERIC
&& DateUtil.isCellDateFormatted(cell);
}
/** 将 2026-07-14 00:00:00、2026/7/14、2026年7月14日 等文本统一为 ISO 日期。 */
private String normalizeTextDate(String value) {
String text = value == null ? "" : value.trim();
Matcher matcher = TEXT_DATE_PATTERN.matcher(text);
if (!matcher.matches()) {
return text;
}
try {
return LocalDate.of(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), Integer.parseInt(matcher.group(3))).toString();
} catch (Exception ex) {
return text;
}
}
private boolean isBlank(Row row) {