Pregunta

I read Excel spreadsheet (.xlsx) with Apache-poi 3.8. When I try to get numeric value from cell at 0 column index, I get wrong numberic value.

For example my table looks like this

+-----------+---------+---------+
| Header1   | Header2 | Header3 |
+-----------+---------+---------+
| 123456789 | AA      | BB      |
|     99999 | CC      | DD      |
+-----------+---------+---------+

I begin to read on Row index 1 and Cell Index 0. It should returns 123456789 but it returns wrong value 13. Next columns are correct even if it's numeric value. If the first cell contains string it returns correct value as well. Row 2 Cell 0 reads like 14 and next columns are correct.

The number I get from first column is somehow related to amount of rows in sheet, If I have 6 rows, it starts to return 16,17,18,19,20. It should not have to be related with other frameworks but I use myfaces tomahawk and jsf 1.2 for upload my Excel file.

public String getCellStr(final int x, final int y) {
    String cellValue = "";
    try {
        Row row = sheet.getRow(x);
        Cell cell = row.getCell(y);
        if (row == null || (row != null && cell == null)) {
            cellValue = "";
        } else {
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                cellValue = cell.toString();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    cellValue = DateUtils.date2String(cell.getDateCellValue());
                } else {
                    Double value = cell.getNumericCellValue();
                    Long longValue = value.longValue();
                    cellValue = longValue.toString();
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                cellValue = new String(new Boolean(
                                  cell.getBooleanCellValue()).toString());
                break;
            case Cell.CELL_TYPE_BLANK:
                cellValue = "";
                break;
            }
        }
    } catch (NullPointerException e) {
        return cellValue;
    }
    return cellValue;
}
¿Fue útil?

Solución

Finally I find my mistake. This code was responsible for the strange behaviour. Apparently I cannot cast cell to other type and cast it back without destroying value.

int cellType = cell.getCellType();
cell.setCellType(Cell.CELL_TYPE_STRING);
String val = cell.getStringCellValue();
cell.setCellType(cellType);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top