使用Apache Poi从Excel工作表中获取单元格值

如何在java中使用poi获取单元格值?

我的代码看起来像这样

String cellformula_total__percentage= "(1-E" + (rowIndex + 2) + "/" + "D" + (rowIndex + 2) + ")*100"; cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); cell.setCellStyle(this.valueRightAlignStyleLightBlueBackground); cell.setCellFormula("abs(" + cellformula_total__percentage + ")"); 

但是,如果在这种情况下,我如何检查我的单元格值是否包含错误值,如#DIV / 0! 以及如何用N / A替换它

您必须使用FormulaEvaluator,如此处所示。 如果单元格包含这样的公式,这将返回一个值,该值是单元格中存在的值或公式的结果:

 FileInputStream fis = new FileInputStream("/somepath/test.xls"); Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("/somepath/test.xls") Sheet sheet = wb.getSheetAt(0); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); // suppose your formula is in B3 CellReference cellReference = new CellReference("B3"); Row row = sheet.getRow(cellReference.getRow()); Cell cell = row.getCell(cellReference.getCol()); if (cell!=null) { switch (evaluator.evaluateFormulaCell(cell)) { case Cell.CELL_TYPE_BOOLEAN: System.out.println(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_NUMERIC: System.out.println(cell.getNumericCellValue()); break; case Cell.CELL_TYPE_STRING: System.out.println(cell.getStringCellValue()); break; case Cell.CELL_TYPE_BLANK: break; case Cell.CELL_TYPE_ERROR: System.out.println(cell.getErrorCellValue()); break; // CELL_TYPE_FORMULA will never occur case Cell.CELL_TYPE_FORMULA: break; } } 

如果您需要精确的含义(即,如果单元格包含公式,则为formla),则此处显示。

编辑:添加了一些示例来帮助您。

首先你得到细胞(只是一个例子)

 Row row = sheet.getRow(rowIndex+2); Cell cell = row.getCell(1); 

如果您只想使用公式将值设置到单元格中(不知道结果):

  String formula ="ABS((1-E"+(rowIndex + 2)+"/D"+(rowIndex + 2)+")*100)"; cell.setCellFormula(formula); cell.setCellStyle(this.valueRightAlignStyleLightBlueBackground); 

如果要在单元格中出现错误时更改消息,则必须更改公式以执行此操作,例如

 IF(ISERR(ABS((1-E3/D3)*100));"N/A"; ABS((1-E3/D3)*100)) 

(此公式检查评估是否返回错误,然后显示字符串“N / A”,或者评估,如果这不是错误)。

如果要获取与公式对应的值,则必须使用求值程序。

希望这个帮助,
纪尧姆

可能是: –

  for(Row row : sheet) { for(Cell cell : row) { System.out.print(cell.getStringCellValue()); } } 

对于特定类型的单元格,您可以尝试:

 switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: cellValue = cell.getStringCellValue(); break; case Cell.CELL_TYPE_FORMULA: cellValue = cell.getCellFormula(); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { cellValue = cell.getDateCellValue().toString(); } else { cellValue = Double.toString(cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_BLANK: cellValue = ""; break; case Cell.CELL_TYPE_BOOLEAN: cellValue = Boolean.toString(cell.getBooleanCellValue()); break; }