lyhzzz 2 ay önce
ebeveyn
işleme
eeff6cf8a1

+ 29 - 6
src/main/java/com/fdkankan/agent/util/ExcelUtil.java

@@ -10,6 +10,8 @@ import org.springframework.web.multipart.MultipartFile;
 import java.io.IOException;
 import java.io.InputStream;
 import java.text.SimpleDateFormat;
+import java.time.LocalDate;
+import java.time.ZoneId;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.HashMap;
@@ -38,12 +40,18 @@ public class ExcelUtil {
             //转换为List数组
             for (int cellNum=0;cellNum<= row.getLastCellNum();cellNum++){
                 Cell cell = row.getCell(cellNum);
-                if (cell != null && cell.getCellTypeEnum() != CellType.STRING && HSSFDateUtil.isCellDateFormatted(cell))
-                {
-                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
-                    Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
-                    String value = sdf.format(date);
-                    map.put(cellNum,value);
+
+
+                if (cell != null && cell.getCellTypeEnum() != CellType.STRING && HSSFDateUtil.isCellDateFormatted(cell)) {
+                    Date date = cell.getDateCellValue();
+                    if (HSSFDateUtil.isValidExcelDate(date.getTime())) {
+                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+                        String value = sdf.format(date);
+                        map.put(cellNum,value);
+                    } else {
+                        map.put(cellNum,"");
+                    }
+
                     continue;
                 }
                 if(cell != null){
@@ -84,7 +92,22 @@ public class ExcelUtil {
     public static boolean isNumeric2(String str) {
         return str != null && str.matches("-?\\d+(\\.\\d+)?");
     }
+    // 综合解决方案示例
+    public static LocalDate getCellLocalDate(Cell cell) {
+        if (cell == null || cell.getCellType() == CellType.BLANK) {
+            return null;
+        }
 
+        if (cell.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)) {
+            Date date = cell.getDateCellValue();
+            if (DateUtil.getExcelDate(date) == 0) {
+                return null;
+            }
+            return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
+        }
+
+        return null;
+    }
 
 
     private static Workbook getExcelWorkBook(InputStream inputStream) throws IOException {