使用java代码读取xl表

时间:2014-02-21 07:15:05

标签: java apache-poi xls

这里我试图通过使用以下java代码来阅读xl表,但是我在阅读单元格时遇到异常,如下所示。

Xl阅读代码

Cell cell14 = row.getCell(14);
int celltype = cell4.getCellType();
if (celltype == HSSFCell.CELL_TYPE_BOOLEAN) {
    System.out.println("inide boolean");
    row.getCell(14).getBooleanCellValue();
    System.out.println("row.getCell(14).getBooleanCellValue()" + row.getCell(14).getBooleanCellValue());
} else if (celltype == HSSFCell.CELL_TYPE_ERROR) {
    System.out.println("inide CELL_TYPE_ERROR");
    row.getCell(14).getErrorCellValue();
    System.out.println("row.getCell(14).getErrorCellValue()" + row.getCell(14).getErrorCellValue());
} else if (celltype == HSSFCell.CELL_TYPE_FORMULA) {
    System.out.println("inide CELL_TYPE_FORMULA");
    row.getCell(14).getCellFormula();
    System.out.println(" row.getCell(14).getCellFormula()" + row.getCell(14).getCellFormula());
} else if (celltype == HSSFCell.CELL_TYPE_NUMERIC) {
    System.out.println("inide CELL_TYPE_NUMERIC");
    row.getCell(14).getNumericCellValue();
    System.out.println("row.getCell(14).getNumericCellValue()" + row.getCell(14).getNumericCellValue());
} else if (celltype == HSSFCell.CELL_TYPE_STRING) {
    System.out.println("inide CELL_TYPE_STRING");
    row.getCell(14).getRichStringCellValue();
    System.out.println("row.getCell(14).getStringCellValue();" + row.getCell(14).getRichStringCellValue());
}

以下是例外

java.lang.IllegalStateException: Cannot get a text value from a numeric cell
    at org.apache.poi.hssf.usermodel.HSSFCell.typeMismatch(HSSFCell.java:643)
    at org.apache.poi.hssf.usermodel.HSSFCell.getRichStringCellValue(HSSFCell.java:720)
    at org.apache.poi.hssf.usermodel.HSSFCell.getRichStringCellValue(HSSFCell.java:67)

1 个答案:

答案 0 :(得分:2)

我认为以下错字可能是问题的原因:

Cell cell14 = row.getCell(14);
int celltype = cell4.getCellType();

可能应该是:

Cell cell14 = row.getCell(14);
int celltype = cell14.getCellType();

(cellType现在基于cell14而不是cell4。)

相关问题