package com.trafficaudit.subsidyaudit.service; import com.trafficaudit.subsidyaudit.dto.SubsidyApplicationRow; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; @Component public class SubsidyApplicationExcelReader { private static final List PLATE_HEADERS = Arrays.asList( "车牌号码", "车牌号", "号牌号码", "新增车辆号牌", "车辆号牌"); private static final List VIN_HEADERS = Arrays.asList( "车辆识别代号", "车架号", "VIN", "新增车辆车架号"); private static final List STANDARD_HEADERS = Arrays.asList( "补贴标准", "申请补贴标准", "补贴金额标准", "补贴标准万元"); private static final List TYPE_HEADERS = Arrays.asList( "申请资金类型", "申请类型", "资金类型", "补贴类型"); public List read(MultipartFile file) { if (file == null || file.isEmpty()) { throw new IllegalArgumentException("请上传申请表 Excel"); } String filename = file.getOriginalFilename() == null ? "" : file.getOriginalFilename().toLowerCase(Locale.ROOT); if (!filename.endsWith(".xlsx") && !filename.endsWith(".xls")) { throw new IllegalArgumentException("申请表必须是 .xlsx 或 .xls 文件"); } try (InputStream input = file.getInputStream(); Workbook workbook = WorkbookFactory.create(input)) { Map columns = null; Sheet targetSheet = null; int headerRowIndex = -1; for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) { Sheet sheet = workbook.getSheetAt(sheetIndex); HeaderMatch match = findHeader(sheet); if (match != null) { targetSheet = sheet; columns = match.columns; headerRowIndex = match.rowIndex; break; } } if (targetSheet == null) { throw new IllegalArgumentException("未找到申请表表头,至少需要车牌号码、车辆识别代号、补贴标准三列"); } return readRows(targetSheet, headerRowIndex, columns); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { throw new IllegalArgumentException("读取申请表失败: " + e.getMessage(), e); } } private HeaderMatch findHeader(Sheet sheet) { int last = Math.min(sheet.getLastRowNum(), 50); DataFormatter formatter = new DataFormatter(Locale.CHINA); for (int rowIndex = 0; rowIndex <= last; rowIndex++) { Row row = sheet.getRow(rowIndex); if (row == null) continue; Map found = new HashMap<>(); for (Cell cell : row) { String value = normalizeHeader(formatter.formatCellValue(cell)); if (value.isEmpty()) continue; matchHeader(found, "plate", value, PLATE_HEADERS, cell.getColumnIndex()); matchHeader(found, "vin", value, VIN_HEADERS, cell.getColumnIndex()); matchHeader(found, "standard", value, STANDARD_HEADERS, cell.getColumnIndex()); matchHeader(found, "type", value, TYPE_HEADERS, cell.getColumnIndex()); } if (found.containsKey("plate") && found.containsKey("vin") && found.containsKey("standard")) { Map columns = new HashMap<>(); columns.put(0, found.get("plate")); columns.put(1, found.get("vin")); columns.put(2, found.get("standard")); if (found.containsKey("type")) columns.put(3, found.get("type")); return new HeaderMatch(rowIndex, columns); } } return null; } private void matchHeader(Map found, String key, String value, List headers, int columnIndex) { if (found.containsKey(key)) return; for (String header : headers) { String normalized = normalizeHeader(header); if (value.equals(normalized) || value.contains(normalized)) { found.put(key, columnIndex); return; } } } private List readRows(Sheet sheet, int headerRowIndex, Map columns) { DataFormatter formatter = new DataFormatter(Locale.CHINA); List rows = new ArrayList<>(); List errors = new ArrayList<>(); Set seenVins = new HashSet<>(); for (int rowIndex = headerRowIndex + 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) { Row row = sheet.getRow(rowIndex); if (row == null) continue; String plate = text(row, columns.get(0), formatter); String vin = normalizeVin(text(row, columns.get(1), formatter)); String standardText = text(row, columns.get(2), formatter); String type = columns.containsKey(3) ? text(row, columns.get(3), formatter) : ""; if (plate.isEmpty() && vin.isEmpty() && standardText.isEmpty() && type.isEmpty()) continue; int excelRow = rowIndex + 1; if (!includeNewVehicle(type)) continue; if (plate.isEmpty()) errors.add("第 " + excelRow + " 行:车牌号码为空"); if (!isValidVin(vin)) errors.add("第 " + excelRow + " 行:车辆识别代号不是 17 位有效 VIN"); if (!seenVins.add(vin)) errors.add("第 " + excelRow + " 行:车辆识别代号重复"); Double standard = parseSubsidyStandard(standardText); if (standard == null) errors.add("第 " + excelRow + " 行:补贴标准无法识别(支持 5.5万元 或 55000元)"); SubsidyApplicationRow item = new SubsidyApplicationRow(); item.setExcelRow(excelRow); item.setPlateNumber(plate.replaceAll("\\s+", "").toUpperCase(Locale.ROOT)); item.setVin(vin); item.setSubsidyStandard(standard == null ? 0.0 : standard); item.setApplicationType(type); rows.add(item); } if (!errors.isEmpty()) { throw new IllegalArgumentException(joinErrors(errors)); } if (rows.isEmpty()) { throw new IllegalArgumentException("申请表未读取到新增车辆数据"); } return rows; } private boolean includeNewVehicle(String type) { String value = type == null ? "" : type.replaceAll("\\s+", ""); if (value.isEmpty()) return true; boolean newVehicle = value.contains("更新") || value.contains("新增") || value.contains("新购") || value.contains("新购置"); if (newVehicle) return true; return !value.contains("报废"); } private Double parseSubsidyStandard(String raw) { if (raw == null || raw.trim().isEmpty()) return null; String value = raw.replace(",", "").replace(",", "").trim(); boolean tenThousand = value.contains("万"); value = value.replace("万元", "").replace("万", "").replace("元", "").trim(); try { double number = Double.parseDouble(value); if (tenThousand || number < 10000.0) number *= 10000.0; return number; } catch (NumberFormatException e) { return null; } } private String text(Row row, Integer column, DataFormatter formatter) { if (column == null || column < 0) return ""; Cell cell = row.getCell(column); return cell == null ? "" : formatter.formatCellValue(cell).trim(); } private String normalizeHeader(String value) { return value == null ? "" : value.replaceAll("[\\s\\p{Punct}()()【】\\[\\]]", "") .replace("(", "").replace(")", "").toUpperCase(Locale.ROOT); } private String normalizeVin(String value) { return value == null ? "" : value.replaceAll("[^A-Za-z0-9]", "").toUpperCase(Locale.ROOT); } private boolean isValidVin(String vin) { return vin != null && vin.matches("[A-HJ-NPR-Z0-9]{17}"); } private String joinErrors(List errors) { int limit = Math.min(errors.size(), 100); StringBuilder builder = new StringBuilder("申请表存在错误:"); for (int i = 0; i < limit; i++) builder.append("\n").append(errors.get(i)); if (errors.size() > limit) builder.append("\n……共 ").append(errors.size()).append(" 行错误"); return builder.toString(); } private static class HeaderMatch { private final int rowIndex; private final Map columns; private HeaderMatch(int rowIndex, Map columns) { this.rowIndex = rowIndex; this.columns = columns; } } }