xyc
2026-11-11 9483eb4f6d7a75261dbde71ace7878df2f7eda07
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
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<String> PLATE_HEADERS = Arrays.asList(
            "车牌号码", "车牌号", "号牌号码", "新增车辆号牌", "车辆号牌");
    private static final List<String> VIN_HEADERS = Arrays.asList(
            "车辆识别代号", "车架号", "VIN", "新增车辆车架号");
    private static final List<String> STANDARD_HEADERS = Arrays.asList(
            "补贴标准", "申请补贴标准", "补贴金额标准", "补贴标准万元");
    private static final List<String> TYPE_HEADERS = Arrays.asList(
            "申请资金类型", "申请类型", "资金类型", "补贴类型");
 
    public List<SubsidyApplicationRow> 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<Integer, Integer> 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<String, Integer> 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<Integer, Integer> 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<String, Integer> found, String key, String value, List<String> 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<SubsidyApplicationRow> readRows(Sheet sheet, int headerRowIndex, Map<Integer, Integer> columns) {
        DataFormatter formatter = new DataFormatter(Locale.CHINA);
        List<SubsidyApplicationRow> rows = new ArrayList<>();
        List<String> errors = new ArrayList<>();
        Set<String> 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<String> 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<Integer, Integer> columns;
 
        private HeaderMatch(int rowIndex, Map<Integer, Integer> columns) {
            this.rowIndex = rowIndex;
            this.columns = columns;
        }
    }
}