@Gagravarr が言ったように、現在 DataFormatter はほとんどのエラーを処理します (私は poi-3.11-beta2 を使用しています)。しかし、私のコメントで述べたように、一部の数式エラーは依然として例外をスローする可能性があります。
たとえば、=xxx()
xxx が実際の関数ではない場合のように数式を評価すると、Excel は表示されます#NAME?
が、「名前 'xxx' を評価する方法がわからない」という実行時例外が発生します。
幸いなことに、処理は簡単です。
public String readCellValue(Cell cell)
{
switch (cell.getCellType())
{
case Cell.CELL_TYPE_BLANK:
return "(blank)";
case Cell.CELL_TYPE_BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
case Cell.CELL_TYPE_ERROR:
return String.valueOf(cell.getErrorCellValue());
case Cell.CELL_TYPE_FORMULA:
return readFormattedCellValue(cell);
case Cell.CELL_TYPE_NUMERIC:
return String.valueOf(cell.getNumericCellValue());
case Cell.CELL_TYPE_STRING:
return cell.getStringCellValue();
default:
return "Unknown type!";
}
}
public String readFormattedCellValue(Cell cell)
{
try
{
return formatter.formatCellValue(cell, evaluator);
}
catch (RuntimeException e)
{
return e.getMessage(); // Error from evaluator, for example "Don't know how to evaluate name 'xxx'" if we have =xxx() in cell
}
}
レコードについては、formatter
CSVevaluator
への変換の例のように作成されます。
try (FileInputStream fis = new FileInputStream(file))
{
// Open the workbook and then create the FormulaEvaluator and
// DataFormatter instances that will be needed to, respectively,
// force evaluation of formulae found in cells and create a
// formatted String encapsulating the cells contents.
workbook = WorkbookFactory.create(fis);
evaluator = workbook.getCreationHelper().createFormulaEvaluator();
formatter = new DataFormatter(true);
}
なんらかの理由で、WorkbookFactory
は poi-3.11-beta2.jar ではなく、poi-ooml-3.11-beta2.jar にのみ存在します。