The following code should be able reading any kind of Excel
cell contents. I hope I have not forgotten something.
Mainly changes to Busy Developers' Guide: Getting the cell contents are:
Using DataFormatter
having a FormulaEvaluator
.
If cell.getCellTypeEnum()
is CellType.FORMULA
then check again the cell.getCachedFormulaResultTypeEnum()
and react dependent of what this is like.
Works using latest stable release Apache POI 3.16
. Works not using lower versions.
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.usermodel.CellType.*;
import java.io.FileInputStream;
class ReadExcelExample {
public static void main(String[] args) throws Exception {
Workbook wb = WorkbookFactory.create(new FileInputStream("ExcelExample.xlsx"));
DataFormatter formatter = new DataFormatter();
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
System.out.print(cellRef.formatAsString());
System.out.print(" - ");
// get the text that appears in the cell by getting the cell value and applying any data formats (Date, 0.00, 1.23e9, $1.23, etc)
String text = "";
try {
text = formatter.formatCellValue(cell, evaluator);
} catch (org.apache.poi.ss.formula.eval.NotImplementedException ex) {
text = "Formula not implemented";
}
System.out.println(text);
// Alternatively, get the value and format it yourself
switch (cell.getCellTypeEnum()) {
case STRING:
System.out.println(cell.getRichStringCellValue().getString());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
System.out.println(cell.getDateCellValue());
} else {
System.out.println(cell.getNumericCellValue());
}
break;
case BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case FORMULA:
System.out.println(cell.getCellFormula());
switch (cell.getCachedFormulaResultTypeEnum()) {
case STRING:
System.out.println(cell.getRichStringCellValue().getString());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
System.out.println(cell.getDateCellValue());
} else {
System.out.println(cell.getNumericCellValue());
}
break;
case BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case ERROR:
System.out.println(cell.getErrorCellValue());
break;
default:
System.out.println("default formula cell"); //should never occur
}
break;
case ERROR:
System.out.println(cell.getErrorCellValue());
break;
case BLANK:
System.out.println("blank");
break;
default:
System.out.println("default cell"); //should never occur
}
}
}
wb.close();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…