使用Apache POI将单元格内容读取为富文本。使用cell.getRichStringCellValue()方法时处理数字单元格

时间:2015-12-10 15:18:28

标签: java apache-poi richtext

我想从Excel电子表格中读取单元格值作为富文本,而不是字符串,但是当单元格类型为数字并且我使用的是cell.getRichStringCellValue()方法时,会抛出异常。处理这个问题的好方法是什么?

1 个答案:

答案 0 :(得分:1)

你需要follow the approach carefully and lovingly laid out in the Apache POI documentation(谁想过?!)。你想要做的事情如下:

import org.apache.poi.ss.usermodel.*;

Workbook wb = WorkbookFactory.create(new File("input.xls"));
Sheet sheet1 = wb.getSheetAt(0);
for (Row row : sheet1) {
    for (Cell cell : row) {
        CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
        System.out.print(cellRef.formatAsString());
        System.out.print(" - ");

        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                RichTextString contents = cell.getRichStringCellValue();
                // TODO Handle contents
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    Date date = cell.getDateCellValue();
                    // TODO Handle Date value
                } else {
                    double number = cell.getNumericCellValue();
                    // TODO Handle number
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                boolean value = cell.getBooleanCellValue();
                // TODO Handle
                break;
            case Cell.CELL_TYPE_FORMULA:
                // Either get formula, or check last value, or evaluate
                break;
            default:
                // Shouldn't happen
        }
    }
}

然后添加您自己的逻辑,以便在您获取内容时处理内容