Pergunta

Eu estou usando POI HSSF API para os meus manipulações do Excel em Java. Eu tenho um valor de data "8/1/2009" em um dos minha cela excel e enquanto eu tento ler este valor usando HSSF API, ele detecta o tipo de célula como numérico e retorna o valor 'Double' da minha data. Consulte o código de exemplo abaixo:

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 () retorna NUMERIC_TYPE e, portanto, este converte o código da data para o dobro! : (

Existe alguma maneira de ler a data como no HSSF POI!?

Foi útil?

Solução

Você poderia dar uma olhada em:

HSSFDateUtil.isCellDateFormatted()

Veja o POI Horrível API formato de planilha para obter mais detalhes sobre HSSFDateUtil:

http://poi.apache.org/ apidocs / org / apache / poi / HSSF / userModel / HSSFDateUtil.html

Isso também fornece alguns métodos auxiliares para o regresso getExcelDate() Excel e Java datas getJavaDate(). Você precisa ser um pouco cuidadoso de diferentes formatos de data embora ...

Outras dicas

Se você deseja fazer referência a data no mesmo formato em que no arquivo do Excel, você deve usar o CellDateFormatter. código de exemplo:

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 trata datas e horas como números ... Jon dito melhor, por isso não vou repetir-lo aqui ...

No entanto, o código de exemplo para o que você colocar na pergunta é em http : //poi.apache.org/spreadsheet/quick-guide.html#CellContents

Se você usar o POI 3.5, você pode usar o seguinte

cell.getDateCellValue () método. Isto irá funcionar para o Excel 2007 também.

Desde POI 3,15 beta3 algumas funções são deprecated. Você pode verificar o formato de dados e recuperar como Date Java.

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());
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top