Domanda

sto usando POI HSSF API per le mie manipolazioni excel in Java. Ho un valore di data "8/1/2009" in uno dei miei cella di Excel e mentre provo a leggere questo valore utilizzando HSSF API, rileva il tipo di cella come numerico e restituisce il valore 'doppio' di mia data. Vedere il codice di esempio riportato di seguito:

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 () restituisce NUMERIC_TYPE e quindi questo codice converte la data di raddoppiare! : (

C'è un modo per leggere la data in quanto è in HSSF POI!?

È stato utile?

Soluzione

Si potrebbe dare un'occhiata a:

HSSFDateUtil.isCellDateFormatted()

Vedere la POI Horrible API foglio elettronico formato per maggiori dettagli su HSSFDateUtil:

http://poi.apache.org/ apidocs / org / apache / PDI / HSSF / usermodel / HSSFDateUtil.html

che fornisce anche alcuni metodi di supporto per la restituzione Excel getExcelDate() e Java date getJavaDate(). Hai bisogno di essere un po 'diffidenti nei confronti di diversi formati di data anche se ...

Altri suggerimenti

Se si desidera fare riferimento alla data nello stesso formato come nel file di Excel, è necessario utilizzare le CellDateFormatter. codice di esempio:

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
}

Excel considera date e orari come numeri ... Jon ha detto meglio, quindi non lo eco qui ...

Tuttavia, il codice di esempio per quello che hai messo in questione è a http : //poi.apache.org/spreadsheet/quick-guide.html#CellContents

Se si utilizza il POI 3.5 è possibile utilizzare il seguente

Metodo

cell.getDateCellValue (). Questo funziona per Excel 2007 pure.

Dal POI 3.15 beta3 alcune funzioni sono deprecated. È possibile controllare il formato dei dati e recuperare come 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());
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top