【问题标题】:why is the date field messing up when im reading from xlsx to java?当我从 xlsx 读取到 java 时,为什么日期字段会混乱?
【发布时间】:2021-11-05 19:01:33
【问题描述】:

我在 excel 中将日期列格式设置为 M/d/yyyy,但是,当我在 Java 中读取单元格值时,日期似乎是“05/Jan/2021”,我对什么感到困惑发生?谁能帮我解决我做错了什么?

XSSFWorkbook wb1 = new XSSFWorkbook(fis1);   
XSSFSheet sheet1 = wb1.getSheetAt(0);     //creating a Sheet object to retrieve object  
Iterator<Row> itr1 = sheet1.iterator();    //iterating over excel file  
ArrayList recipientids = new ArrayList();

for (Row row : sheet1) { // For each Row.
    Cell cell = row.getCell(4); // Get the Cell at the Index / Column you want.
    Cell cell2 = row.getCell(5);
    CellType type = cell2.getCellType();
    if (type == CellType.NUMERIC) {
        Date date = new Date();
        SimpleDateFormat DateFor = new SimpleDateFormat("M/d/yyyy");
              String dateString = cell2.toString();
        String newdate = dateString.replace("-", "/");

        arraylist.add(cell+"-"+newdate);
    }
}

但是,当我尝试格式化时,我无法格式化/解析异常。

【问题讨论】:

  • 不要再使用SimpleDateFormat。它已经过时了这么多年了......
  • 你能给我建议吗?

标签: java excel oop logic structure


【解决方案1】:

如前所述,不要使用SimpleDateFormat 甚至Date。自 Java 8 以来,Java 中有一个新的日期和时间 API。

检查以下内容,可能会有所帮助:

XSSFWorkbook wb1 = new XSSFWorkbook(fis1);   
XSSFSheet sheet1 = wb1.getSheetAt(0);     //creating a Sheet object to retrieve object  
Iterator<Row> itr1 = sheet1.iterator();    //iterating over excel file  
ArrayList recipientids = new ArrayList();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("M/d/yyyy");

for (Row row : sheet1) { // For each Row.
    Cell cell = row.getCell(4); // Get the Cell at the Index / Column you want.
    Cell cell2 = row.getCell(5);
    CellType type = cell2.getCellType();
    if (type == CellType.NUMERIC) {
        String dateString = cell2.toString();
        LocalDate date = LocalDate.parse(dateString, dateTimeFormatter);
        System.out.println(date.format(dateTimeFormatter)); // Formats this date using the specified formatter.
    }
}

【讨论】:

  • @NewBond007,这有帮助吗?如果有不清楚的地方请告诉我。
猜你喜欢
  • 2022-11-25
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-15
  • 2018-11-05
  • 2017-08-08
  • 1970-01-01
相关资源
最近更新 更多