读取excel数据有误
在对excel单元格取数据时,如果直接进行String.value()或者直接toString(),在对有格式的单元格中取出来的数据 往往是不尽人意的
例如:excel数据中是 2023/1/1
读出来可能是 2023年1月1号
date转换是有问题的 原因就是因为读取时 把格式也一起读取出来了
格式化从excel单元格中读取出来的数据
public static final String REGEX = "\n";
private String getCellValue(Cell cell) {
Object cellValue;
if (cell != null) {
cellValue = cellValue(cell);
} else {
cellValue = "";
}
return String.valueOf(cellValue);
}
private Object cellValue(Cell cell) {
Object cellValue;
switch (cell.getCellType()) {
case NUMERIC: {
cellValue = date(cell);
break;
}
case FORMULA: {
cellValue = formula(cell);
break;
}
case STRING: {
cellValue = cell.getRichStringCellValue().getString().replaceAll(REGEX, " ") ;
break;
}
default:
cellValue = cell.getStringCellValue();
}
return cellValue;
}
private Object formula(Cell cell) {
Object cellValue = null;
try {
cellValue = date(cell);
} catch (Exception e) {
if (e.getMessage().contains(STRING)) {
cellValue = cell.getRichStringCellValue().getString().replaceAll(REGEX, " ");
}
}
return cellValue;
}
private Object date(Cell cell) {
Object cellValue;
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = cell.getDateCellValue();
cellValue = cellDate(cellValue);
} else {
cell.setCellType(CellType.STRING);
cellValue = cell.getRichStringCellValue();
}
return String.valueOf(cellValue).replaceAll(REGEX, " ");
}
private Object cellDate(Object cellValue) {
DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
cellValue = formater.format(cellValue);
return cellValue;
}