POI DataFormatter returns 2 digits year instead of 4 digits year for date cells [duplicate]

In Excel Cell Style issue I have shown that if a date in Excel which is formatted using the default date format (Short Date) only has the format id 0xE (14) stored in the file and there is not a format pattern stored anywhere. So how Short Date will be displayed in Excel depends on the locale settings of the system.

How working around this issue without using Apache POI’s DataFormatter is also shown in that answer.

Using Apache POI’s DataFormatter we can work around this issue with customizing the DataFormatter.

Example:

Excel:

enter image description here

Code:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.LocaleUtil;

import java.io.FileInputStream;

class ExcelDataformatterCustomized {

 public static void main(String[] args) throws Exception {

  Workbook wb  = WorkbookFactory.create(new FileInputStream("ExcelExample.xlsx"));

  LocaleUtil.setUserLocale(java.util.Locale.GERMANY);
  //LocaleUtil.setUserLocale(java.util.Locale.US);
  //LocaleUtil.setUserLocale(java.util.Locale.UK);

  DataFormatter df = new DataFormatter();
  FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();

  if (LocaleUtil.getUserLocale().equals(java.util.Locale.GERMANY)) {
   df.addFormat("m/d/yy", new java.text.SimpleDateFormat("dd.MM.yyyy"));
  } else if (LocaleUtil.getUserLocale().equals(java.util.Locale.US)) {
   df.addFormat("m/d/yy", new java.text.SimpleDateFormat("M/d/yyyy"));
  } else if (LocaleUtil.getUserLocale().equals(java.util.Locale.UK)) {
   df.addFormat("m/d/yy", new java.text.SimpleDateFormat("dd/MM/yyyy"));
  }

  Sheet sheet = wb.getSheetAt(0);
  for (Row row : sheet) {
   for (Cell cell : row) {

     String value = df.formatCellValue(cell, evaluator);
     System.out.println(value);

   }
  }
  wb.close();
 }
}

Result having java.util.Locale.GERMANY set:

Short Date
12.08.2018
Formatted Date
Sonntag, August 12, 2018

Result having java.util.Locale.US set:

Short Date
8/12/2018
Formatted Date
Sunday, August 12, 2018

Result having java.util.Locale.UK set:

Short Date
12/08/2018
Formatted Date
Sunday, August 12, 2018

Leave a Comment