Wenn ich Zelleninhalte mit der Apache-POI-Bibliothek erhalte, bekomme ich beides: "Kann keinen numerischen Wert von einer Textzelle bekommen" und umgekehrt. Wie repariere ich es?

Merke ich, die Frage ist ein wenig verwirrend, aber ich wusste nicht wie sonst zu Wort. Wie auch immer, hier ist der original code:

private void readFile(String excelFileName) throws FileNotFoundException, IOException {
    XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(excelFileName));
    if (workbook.getNumberOfSheets() > 1){
        System.out.println("Please make sure there is only one sheet in the excel workbook.");
    }
    XSSFSheet sheet = workbook.getSheetAt(0);
    int numOfPhysRows = sheet.getPhysicalNumberOfRows();
    XSSFRow row;
    XSSFCell num;
    for(int y = 1;y < numOfPhysRows;y++){    //start at the 2nd row since 1st should be category names
        row = sheet.getRow(y);
        poNum = row.getCell(1);
        item = new Item(Integer.parseInt(poNum.getStringCellValue());
        itemList.add(item);
        y++;
    }
}

private int poiConvertFromStringtoInt(XSSFCell cell){
    int x = Integer.parseInt(Double.toString(cell.getNumericCellValue()));
    return x;
}

Ich erhalte die folgende Fehlermeldung:

Exception in thread "main" java.lang.IllegalStateException: Cannot get a numeric value from a text cell
    at org.apache.poi.xssf.usermodel.XSSFCell.typeMismatch(XSSFCell.java:781)
    at org.apache.poi.xssf.usermodel.XSSFCell.getNumericCellValue(XSSFCell.java:199)

Selbst wenn ich es ändern, um entweder einen string mit XSSFCell.getStringCellValue() oder sogar XFFSCell.getRichTextValue bekomme ich die Umkehrung der oben genannten Fehlermeldung (und ich bin dafür, dass letztlich machen es zu einem int mit Integer.parseInt(XSSFCell.getStringCellValue()).

Den Fehler dann liest:

Exception in thread "main" java.lang.IllegalStateException: Cannot get a text value from a numeric cell
    at org.apache.poi.xssf.usermodel.XSSFCell.typeMismatch(XSSFCell.java:781)
    at org.apache.poi.xssf.usermodel.XSSFCell.getNumericCellValue(XSSFCell.java:199)

Ich weiß, für eine Tatsache, dass die excel-Tabelle die Spalte ist in der Tat eine Zeichenfolge. Ich kann nicht ändern das excel-sheet, wie es hochgeladen wird, wo sonst immer mit dem gleichen format und Formatierung jeder einzelnen Spalte zuerst nimmt zu viel Verarbeitungszeit.

Irgendwelche Vorschläge?

[Lösung] Hier ist die Lösung, code kam ich mit von @Wivani Hilfe:

private long poiGetCellValue(XSSFCell cell){
    long x;
    if(cell.getCellType() == 0)
        x = (long)cell.getNumericCellValue();
    else if(cell.getCellType() == 1)
        x = Long.parseLong(cell.getStringCellValue());
    else
        x = -1;
    return x;
}

InformationsquelleAutor der Frage crstamps2 | 2011-06-28

Schreibe einen Kommentar