fix: 识别 Excel 字段类型

This commit is contained in:
taojinlong 2021-05-25 12:48:06 +08:00
parent ee3c99e177
commit d5c99e6ec9

View File

@ -572,6 +572,7 @@ public class DataSetTableService {
return 0; return 0;
case "TIME": case "TIME":
return 1; return 1;
case "LONG":
case "INT": case "INT":
return 2; return 2;
case "DOUBLE": case "DOUBLE":
@ -778,12 +779,39 @@ public class DataSetTableService {
inputStream.close(); inputStream.close();
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
inferFieldType(fields, data);
map.put("fields", fields); map.put("fields", fields);
map.put("data", jsonArray); map.put("data", jsonArray);
map.put("sheets", sheets); map.put("sheets", sheets);
return map; return map;
} }
private void inferFieldType(List<TableFiled> fields, List<String[]> data){
if(CollectionUtils.isEmpty(fields) || CollectionUtils.isEmpty(data)) {
return;
}
String[] firstLine = data.get(0);
for (int i=0; i< fields.size()&& i < firstLine.length; i++) {
TableFiled filed = fields.get(i);
try{
Integer.valueOf(firstLine[i]);
filed.setFieldType("INT");
continue;
}catch (Exception ignore ){
}
try{
Long.valueOf(firstLine[i]);
filed.setFieldType("LONG");
continue;
}catch (Exception ignore ){}
try{
Double.valueOf(firstLine[i]);
filed.setFieldType("DOUBLE");
continue;
}catch (Exception ignore ){}
}
}
private String readCell(Cell cell) { private String readCell(Cell cell) {
CellType cellTypeEnum = cell.getCellTypeEnum(); CellType cellTypeEnum = cell.getCellTypeEnum();
if (cellTypeEnum.equals(CellType.STRING)) { if (cellTypeEnum.equals(CellType.STRING)) {
@ -791,7 +819,8 @@ public class DataSetTableService {
} else if (cellTypeEnum.equals(CellType.NUMERIC)) { } else if (cellTypeEnum.equals(CellType.NUMERIC)) {
double d = cell.getNumericCellValue(); double d = cell.getNumericCellValue();
try { try {
return new Double(d).longValue() + ""; String value = String.valueOf(d);
return value.endsWith(".0") ? value.substring(0, value.length() -2):value;
} catch (Exception e) { } catch (Exception e) {
BigDecimal b = new BigDecimal(d); BigDecimal b = new BigDecimal(d);
return b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + ""; return b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "";