org.apache.poi Code Samples
Page of 1 |
Prev
|
Next
How do I check if a cell contains a date value?
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 methos will check
if the cell value is a valid date.
package org.kodejava.example.poi;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class DateCellType {
public static void main(String[] args) throws Exception {
String filename = "..\\datecelltype.xls";
FileInputStream fis = null;
try {
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() == HSSFCell.CELL_TYPE_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();
} finally {
if (fis != null) {
fis.close();
}
}
}
}