poi – 安全地把cell当作string读出来

如果cell并非string类型,调用cell.getStringCellValue()会出错。

下面这样可以保证安全:

	
	private String readString(Cell cell) {
		if (cell == null) {
			return null;
		}
		int cellType = cell.getCellType();

		if (cellType == Cell.CELL_TYPE_BLANK) {
			return null;
		}

		if (cellType == Cell.CELL_TYPE_BOOLEAN) {
			return String.valueOf(cell.getBooleanCellValue());
		}

		if (cellType == Cell.CELL_TYPE_ERROR) {
			return null;
		}

		if (cellType == Cell.CELL_TYPE_FORMULA) {
			return cell.getCellFormula();
		}

		if (cellType == Cell.CELL_TYPE_NUMERIC) {
			return String.valueOf(cell.getNumericCellValue());
		}

		if (cellType == Cell.CELL_TYPE_STRING) {
			return cell.getStringCellValue();
		}

		return null;
	}

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.