The code below check if the first cell of an Excel file contains a date value. In Excel the cell type for date is returned as HSSFCell.CELL_TYPE_NUMERIC
, to make sure if it contains a date we can use a utility method HSSFDateUtil.isCellDateFormatted(HSSFCell cell)
, this method will check if the cell value is a valid date.
package org.kodejava.example.poi;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class DateCellType {
public static void main(String[] args) throws Exception {
String filename = "datecelltype.xls";
try (FileInputStream fis = new FileInputStream(filename)) {
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);
// Read a cell the first cell on the sheet.
HSSFCell cell = sheet.getRow(0).getCell(0);
if (cell.getCellType() == CellType.NUMERIC) {
System.out.println("Cell type for date data type is numeric.");
}
// Using HSSFDateUtil to check if a cell contains a date.
if (HSSFDateUtil.isCellDateFormatted(cell)) {
System.out.println("The cell contains a date value: "
+ cell.getDateCellValue());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
The example result of the code snippet:
Cell type for date data type is numeric.
The cell contains a date value: Tue Jul 23 00:00:00 WITA 2019
Maven Dependencies
<!-- https://search.maven.org/remotecontent?filepath=org/apache/poi/poi/4.1.0/poi-4.1.0.jar -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
Wayan Saryada
Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳
Latest posts by Wayan Saryada (see all)
- How do I set the time of java.util.Date instance to 00:00:00? - October 24, 2019
- How to Install Consolas Font in Mac OS X? - March 29, 2019
- How do I clear the current command line in terminal? - February 14, 2019
I have both numeric cells and date cells in my spreadsheet. When I read then using POI, all of them are identified as Date type. How can I differentiate between numeric values and date values?