2009-05-14 14 views
30

Estoy utilizando la API de POI HSSF para mis manipulaciones de Excel en Java. Tengo un valor de fecha "01/08/2009" en una de mis celdas de Excel y mientras trato de leer este valor usando la API HSSF, detecta el tipo de celda como Numérico y devuelve el valor "Doble" de mi fecha. Ver el código de ejemplo siguiente:Lectura de los valores de fecha desde la celda de excel utilizando POI HSSF API

cell = row.getCell(); // date in the cell '8/1/2009' 
switch (cell.getCellType()) { 

case HSSFCell.CELL_TYPE_STRING: 
    cellValue = cell.getRichStringCellValue().getString(); 
    break; 
case HSSFCell.CELL_TYPE_NUMERIC: 
    cellValue = new Double(cell.getNumericCellValue()).toString(); 
    break; 
default: 
} 

Cell.getCellType() devuelve NUMERIC_TYPE y por lo tanto el código convierte la fecha a doble! :(

¿Hay alguna manera de leer la fecha, ya que es en HSSF PDI

Respuesta

37

Usted puede echar un vistazo a:?

HSSFDateUtil.isCellDateFormatted() 

Ver el POI horrible API hoja de cálculo Formato para más detalles en HSSFDateUtil:

http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFDateUtil.html

Eso también proporciona algunos métodos de ayuda para el retorno de Excel getExcelDate() y Java data getJavaDate(). Tienes que ser un poco cuidadoso de diferentes formatos de fecha aunque ...

+8

deseo los desarrolladores de puntos de interés se comentan su código fuente ... Jon

+2

Calling DateUtil.isCellDateFormatted() será un paso adelante en el camino de la liberación de su código de HSSFs y XSSFs. Al utilizar padres globales en lugar de niños HSSF/XSSF dependientes de XLS/XLSX, puede hacer que su código sea mucho más universal. –

6

Si el uso de la PDI 3.5 se puede utilizar el método siguiente

cell.getDateCellValue(). Esto también funcionará para Excel 2007.

20

Si desea hacer referencia a la fecha en el mismo formato que en el archivo de Excel, debe usar CellDateFormatter. Código de ejemplo:

CellValue cValue = formulaEv.evaluate(cell); 
double dv = cValue.getNumberValue(); 
if (HSSFDateUtil.isCellDateFormatted(cell)) { 
    Date date = HSSFDateUtil.getJavaDate(dv); 

    String dateFmt = cell.getCellStyle().getDataFormatString(); 
    /* strValue = new SimpleDateFormat(dateFmt).format(date); - won't work as 
    Java fmt differs from Excel fmt. If Excel date format is mm/dd/yyyy, Java 
    will always be 00 for date since "m" is minutes of the hour.*/ 

    strValue = new CellDateFormatter(dateFmt).format(date); 
    // takes care of idiosyncrasies of Excel 
} 
+0

De esta manera obtiene valores de columnas sin formato que tienen sentido ... – Makky

0

Desde POI 3,15 beta3 algunas funciones son deprecated. Puede verificar el formato de los datos y recuperarlos como Java Date.

SimpleDateFormat format = new SimpleDateFormat(""); 
String cellValue; 
if(cell != null && cell.getCellTypeEnum() != CellType.STRING && 
    cell.getCellTypeEnum() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)){ 

    cellValue = format.format(cell.getDateCellValue()); 
} 
Cuestiones relacionadas