// import org.apache.poi.ss.usermodel.*;
Sheet sheet1 = wb.getSheetAt(0);
for (Row row : sheet1) {
for (Cell cell : row) {
CellReference cellRef = new CellReference(row.getRowNum(), cell.getCellNum());
System.out.print(cellRef.formatAsString());
System.out.print(" - ");
//判断单元格类型
switch(cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getRichStringCellValue().getString());
break;
case Cell.CELL_TYPE_NUMERIC:
if(DateUtil.isCellDateFormatted(cell)) {
System.out.println(cell.getDateCellValue());
} else {
System.out.println(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
System.out.println(cell.getCellFormula());
break;
default:
System.out.println();
}
}
}
要想获得单元格内的内容,您首先要要知道单元格内容的格式(比如您想获得从字符格式的单元格内获得一个数字,您将得到的是NumberFormatException错误)。因此,您将希望能够切换到该单元格格式,然后为获得该单元格内容调用合适的getter方法。在以下的代码中我们将对一个sheet页中的所有单元格进行遍历,并打印出单元格的引用和内容。