xyc
2026-11-12 cb13d459288e2732cb7adc30a8cf80121e3216db
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package com.trafficaudit.dataimport.service;
 
import com.trafficaudit.dataimport.entity.CityTaxiAuth;
import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFRequest;
import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.BoolErrRecord;
import org.apache.poi.hssf.record.EOFRecord;
import org.apache.poi.hssf.record.ExtendedFormatRecord;
import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.FormatRecord;
import org.apache.poi.hssf.record.LabelRecord;
import org.apache.poi.hssf.record.LabelSSTRecord;
import org.apache.poi.hssf.record.MulRKRecord;
import org.apache.poi.hssf.record.NumberRecord;
import org.apache.poi.hssf.record.RKRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.RecordFactory;
import org.apache.poi.hssf.record.RowRecord;
import org.apache.poi.hssf.record.SSTRecord;
import org.apache.poi.hssf.record.StringRecord;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
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.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
 
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
 
public class CityTaxiAuthWorkbookParser {
    private static final byte[] OLE2_SIGNATURE = new byte[] {
        (byte) 0xD0, (byte) 0xCF, 0x11, (byte) 0xE0,
        (byte) 0xA1, (byte) 0xB1, 0x1A, (byte) 0xE1
    };
    private static final int LAST_REQUIRED_COLUMN = 20;
    private static final DataFormatter FORMATTER = new DataFormatter(Locale.CHINA);
 
    public List<CityTaxiAuth> parse(InputStream source) throws IOException {
        BufferedInputStream input = source instanceof BufferedInputStream
            ? (BufferedInputStream) source
            : new BufferedInputStream(source, 1024 * 1024);
        byte[] signature = readSignature(input);
        if (Arrays.equals(signature, OLE2_SIGNATURE)) {
            return parseLegacyXls(input);
        }
        return parseWorkbook(input);
    }
 
    private List<CityTaxiAuth> parseLegacyXls(InputStream input) throws IOException {
        try (POIFSFileSystem fs = new POIFSFileSystem(input)) {
            CityTaxiAuthRecordListener listener = new CityTaxiAuthRecordListener();
            FormatTrackingHSSFListener formattingListener =
                new FormatTrackingHSSFListener(listener, Locale.CHINA);
            listener.setFormattingListener(formattingListener);
 
            HSSFRequest request = new HSSFRequest();
            request.addListenerForAllRecords(formattingListener);
            new HSSFEventFactory().processWorkbookEvents(request, fs.getRoot());
            return listener.finish();
        }
    }
 
    private List<CityTaxiAuth> parseWorkbook(InputStream input) throws IOException {
        try (Workbook workbook = WorkbookFactory.create(input)) {
            if (workbook.getNumberOfSheets() == 0) throw headerError();
            Sheet sheet = workbook.getSheetAt(0);
            requireHeader(sheet);
 
            List<CityTaxiAuth> rows = new ArrayList<>(Math.max(16, sheet.getLastRowNum()));
            for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                if (row == null) continue;
                String plate = getString(row, 0);
                if (plate == null) continue;
                CityTaxiAuth item = new CityTaxiAuth();
                item.setPlateNo(plate.trim());
                item.setVehicleType(getString(row, 1));
                item.setBizType(getString(row, 2));
                item.setOwnerName(getString(row, 3));
                item.setLicenseNo(getString(row, 4));
                item.setFuelType(getString(row, 7));
                item.setArchiveNo(getString(row, 8));
                item.setRoadCertNo(getString(row, 9));
                item.setOperatorName(getString(row, 17));
                item.setOperatorAddr(getString(row, 18));
                item.setOpStatus(getString(row, 19));
                item.setCertStatus(getString(row, 20));
                rows.add(item);
            }
            return rows;
        }
    }
 
    private CityTaxiAuth toEntity(String[] values, String plate) {
        CityTaxiAuth item = new CityTaxiAuth();
        item.setPlateNo(plate.trim());
        item.setVehicleType(cell(values, 1));
        item.setBizType(cell(values, 2));
        item.setOwnerName(cell(values, 3));
        item.setLicenseNo(cell(values, 4));
        item.setFuelType(cell(values, 7));
        item.setArchiveNo(cell(values, 8));
        item.setRoadCertNo(cell(values, 9));
        item.setOperatorName(cell(values, 17));
        item.setOperatorAddr(cell(values, 18));
        item.setOpStatus(cell(values, 19));
        item.setCertStatus(cell(values, 20));
        return item;
    }
 
    private void requireHeader(Sheet sheet) {
        Row header = sheet.getRow(0);
        if (header == null) throw headerError();
        for (Cell cell : header) {
            String value = FORMATTER.formatCellValue(cell);
            if (value != null && value.contains("车牌")) return;
        }
        throw headerError();
    }
 
    private void requireHeader(String[] header) {
        for (String value : header) {
            if (value != null && value.contains("车牌")) return;
        }
        throw headerError();
    }
 
    private IllegalStateException headerError() {
        return new IllegalStateException("所选数据类型【出租车运政车辆】与文件内容不符"
            + ":表头未包含【车牌】等列,请确认是否选错了数据类型");
    }
 
    private String getString(Row row, int index) {
        Cell cell = row.getCell(index);
        if (cell == null) return null;
        if (cell.getCellType() == CellType.FORMULA
                && cell.getCachedFormulaResultType() == CellType.STRING) {
            String cached = cell.getStringCellValue();
            cached = cached == null ? null : cached.trim();
            return cached == null || cached.isEmpty() ? null : cached;
        }
        String value = FORMATTER.formatCellValue(cell).trim();
        return value.isEmpty() ? null : value;
    }
 
    private String cell(String[] values, int index) {
        if (index >= values.length) return null;
        String value = values[index];
        if (value == null) return null;
        value = value.trim();
        return value.isEmpty() ? null : value;
    }
 
    private byte[] readSignature(BufferedInputStream input) throws IOException {
        input.mark(8);
        byte[] signature = new byte[8];
        int offset = 0;
        while (offset < signature.length) {
            int read = input.read(signature, offset, signature.length - offset);
            if (read < 0) break;
            offset += read;
        }
        input.reset();
        if (offset < signature.length) {
            throw new IOException("文件内容为空或格式不完整");
        }
        return signature;
    }
 
    private final class CityTaxiAuthRecordListener implements HSSFListener {
        private final List<CityTaxiAuth> rows = new ArrayList<>(65536);
        private final List<String> headerValues = new ArrayList<>();
        private FormatTrackingHSSFListener formattingListener;
        private SSTRecord sharedStrings;
        private boolean activeSheet = true;
        private boolean headerSeen;
        private int worksheetIndex = -1;
        private int currentRow = -1;
        private String[] currentValues;
        private int pendingFormulaRow = -1;
        private int pendingFormulaColumn = -1;
 
        private void setFormattingListener(FormatTrackingHSSFListener formattingListener) {
            this.formattingListener = formattingListener;
        }
 
        @Override
        public void processRecord(Record record) {
            if (record instanceof SSTRecord) {
                sharedStrings = (SSTRecord) record;
                return;
            }
            if (record instanceof BOFRecord) {
                BOFRecord bof = (BOFRecord) record;
                if (bof.getType() == BOFRecord.TYPE_WORKSHEET) {
                    worksheetIndex++;
                    activeSheet = worksheetIndex == 0;
                }
                return;
            }
            if (record instanceof EOFRecord) {
                if (activeSheet) {
                    finishRow();
                    activeSheet = false;
                }
                return;
            }
            if (!activeSheet) return;
 
            if (record instanceof RowRecord) {
                // RowRecord is row metadata in this BIFF stream. Cell records define
                // the actual row transition and must be allowed to arrive first.
            } else if (record instanceof LabelSSTRecord) {
                LabelSSTRecord cell = (LabelSSTRecord) record;
                startRowIfNeeded(cell.getRow());
                String value = null;
                if (sharedStrings != null) {
                    value = sharedStrings.getString(cell.getSSTIndex()).getString();
                }
                setCell(cell.getRow(), cell.getColumn(), value);
            } else if (record instanceof LabelRecord) {
                LabelRecord cell = (LabelRecord) record;
                setCell(cell.getRow(), cell.getColumn(), cell.getValue());
            } else if (record instanceof NumberRecord) {
                NumberRecord cell = (NumberRecord) record;
                setCell(cell.getRow(), cell.getColumn(), formattingListener.formatNumberDateCell(cell));
            } else if (record instanceof RKRecord) {
                RKRecord cell = (RKRecord) record;
                setCell(cell.getRow(), cell.getColumn(), formattingListener.formatNumberDateCell(cell));
            } else if (record instanceof MulRKRecord) {
                for (NumberRecord number : RecordFactory.convertRKRecords((MulRKRecord) record)) {
                    setCell(number.getRow(), number.getColumn(),
                        formattingListener.formatNumberDateCell(number));
                }
            } else if (record instanceof FormulaRecord) {
                FormulaRecord cell = (FormulaRecord) record;
                startRowIfNeeded(cell.getRow());
                if (cell.hasCachedResultString()) {
                    pendingFormulaRow = cell.getRow();
                    pendingFormulaColumn = cell.getColumn();
                    setCell(cell.getRow(), cell.getColumn(), null);
                } else {
                    setCell(cell.getRow(), cell.getColumn(), formattingListener.formatNumberDateCell(cell));
                }
            } else if (record instanceof StringRecord) {
                if (pendingFormulaRow >= 0) {
                    setCell(pendingFormulaRow, pendingFormulaColumn, ((StringRecord) record).getString());
                    pendingFormulaRow = -1;
                    pendingFormulaColumn = -1;
                }
            } else if (record instanceof BoolErrRecord) {
                BoolErrRecord cell = (BoolErrRecord) record;
                String value = cell.isBoolean()
                    ? Boolean.toString(cell.getBooleanValue())
                    : Byte.toString(cell.getErrorValue());
                setCell(cell.getRow(), cell.getColumn(), value);
            }
        }
 
        private List<CityTaxiAuth> finish() {
            finishRow();
            if (!headerSeen) {
                throw headerError();
            }
            return rows;
        }
 
        private void startRowIfNeeded(int row) {
            if (currentRow != row) startRow(row);
        }
 
        private void startRow(int row) {
            finishRow();
            currentRow = row;
            currentValues = new String[LAST_REQUIRED_COLUMN + 1];
        }
 
        private void finishRow() {
            if (currentRow < 0) return;
            if (currentRow == 0) {
                requireHeader(headerValues.toArray(new String[0]));
                headerSeen = true;
            } else {
                String plate = cell(currentValues, 0);
                if (plate != null) {
                    rows.add(toEntity(currentValues, plate));
                }
            }
            currentRow = -1;
            currentValues = null;
        }
 
        private void setCell(int row, int column, String rawValue) {
            startRowIfNeeded(row);
            String value = normalize(rawValue);
            if (row == 0) {
                while (headerValues.size() <= column) headerValues.add(null);
                headerValues.set(column, value);
            } else if (column >= 0 && column <= LAST_REQUIRED_COLUMN) {
                currentValues[column] = value;
            }
        }
 
        private String normalize(String value) {
            if (value == null) return null;
            String trimmed = value.trim();
            return trimmed.isEmpty() ? null : trimmed;
        }
    }
}