POI读取Excel表格数据类型判断与取值

常量 说明 取值
Cell.CELL_TYPE_NUMERIC 数值类型 cellValue.getNumberValue()
Cell.CELL_TYPE_STRING 字符串类型 cellValue.getStringValue()
Cell.CELL_TYPE_BOOLEAN 布尔类型 cellValue.getBooleanValue()
Cell.CELL_TYPE_FORMULA 表达式类型 需要转换
Cell.CELL_TYPE_ERROR 异常类型 cellValue.getErrorCellValue()
Cell.CELL_TYPE_BLANK  

具体取值:

FileInputStream fis = new FileInputStream("c:/temp/test.xls");
Workbook wb = new HSSFWorkbook(fis); // or new XSSFWorkbook("c:/temp/test.xls")
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();

for (int j = 0; j < sheet.getLastRowNum() + 1; j++) {// getLastRowNum,获取最后一行的行标
	HSSFRow row = sheet.getRow(j);
	if (row != null) {
		for (int k = 0; k < row.getLastCellNum(); k++) {// getLastCellNum,是获取最后一个不为空的列是第几个
			if (row.getCell(k) != null) { // getCell 获取单元格数据
				switch (row.getCell(k).getCellType()) {
				case Cell.CELL_TYPE_BOOLEAN:
					System.out.println(row.getCell(k).getBooleanValue());
					break;
				case Cell.CELL_TYPE_NUMERIC:
					System.out.println(row.getCell(k).getNumberValue());
					break;
				case Cell.CELL_TYPE_STRING:
					System.out.println(row.getCell(k).getStringValue());
					break;
				case Cell.CELL_TYPE_BLANK:
					break;
				case Cell.CELL_TYPE_ERROR:
					System.out.println(row.getCell(k).getErrorCellValue());
					break;
				case Cell.CELL_TYPE_FORMULA:
					System.out.println(evaluator.evaluate(row.getCell(k)).getNumberValue());
					break;
				}
				System.out.print(row.getCell(k) + "\t");
			} else {
				System.out.print("\t");
			}
		}
	}
	System.out.println(""); // 读完一行后换行
}



你可能感兴趣的:(POI读取Excel表格数据类型判断与取值)