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;
|
}
|
}
|
}
|