`
li.feixiang
  • 浏览: 121265 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Formula Evaluation

 
阅读更多

Using FormulaEvaluator.evaluate(Cell cell)

This evaluates a given cell, and returns the new value, without affecting the cell

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();

// suppose your formula is in B3
CellReference cellReference = new CellReference("B3"); 
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol()); 

CellValue cellValue = evaluator.evaluate(cell);

switch (cellValue.getCellType()) {
    case Cell.CELL_TYPE_BOOLEAN:
        System.out.println(cellValue.getBooleanValue());
        break;
    case Cell.CELL_TYPE_NUMERIC:
        System.out.println(cellValue.getNumberValue());
        break;
    case Cell.CELL_TYPE_STRING:
        System.out.println(cellValue.getStringValue());
        break;
    case Cell.CELL_TYPE_BLANK:
        break;
    case Cell.CELL_TYPE_ERROR:
        break;

    // CELL_TYPE_FORMULA will never happen
    case Cell.CELL_TYPE_FORMULA: 
        break;
}				
        

Thus using the retrieved value (of type FormulaEvaluator.CellValue - a nested class) returned by FormulaEvaluator is similar to using a Cell object containing the value of the formula evaluation. CellValue is a simple value object and does not maintain reference to the original cell.

Using FormulaEvaluator.evaluateFormulaCell(Cell cell)

evaluateFormulaCell (Cell cell) will check to see if the supplied cell is a formula cell. If it isn't, then no changes will be made to it. If it is, then the formula is evaluated. The value for the formula is saved alongside it, to be displayed in excel. The formula remains in the cell, just with a new value

The return of the function is the type of the formula result, such as Cell.CELL_TYPE_BOOLEAN

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;
    }
}
				

Using FormulaEvaluator.evaluateInCell(Cell cell)

evaluateInCell (Cell cell) will check to see if the supplied cell is a formula cell. If it isn't, then no changes will be made to it. If it is, then the formula is evaluated, and the new value saved into the cell, in place of the old formula.

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.evaluateInCell
(cell).getCellType()) {
        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;
    }
}

        

Re-calculating all formulas in a Workbook

FileInputStream fis = new FileInputStream("/somepath/test.xls");
Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("/somepath/test.xls")
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
for(int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) {
    Sheet sheet = wb.getSheetAt(sheetNum);
    for(Row r : sheet) {
        for(Cell c : r) {
            if(c.getCellType() == Cell.CELL_TYPE_FORMULA) {
                evaluator.evaluateFormulaCell(c);
            }
        }
    }
}
        

Alternately, if you know which of HSSF or XSSF you're working with, then you can call the static evaluateAllFormulaCells method on the appropriate HSSFFormulaEvaluator or XSSFFormulaEvaluator class.

Recalculation of Formulas

In certain cases you may want to force Excel to re-calculate formulas when the workbook is opened. Consider the following example:

Open Excel and create a new workbook. On the first sheet set A1=1, B1=1, C1=A1+B1. Excel automatically calculates formulas and the value in C1 is 2. So far so good.

Now modify the workbook with POI:

  Workbook wb = WorkbookFactory.create(new FileInputStream("workbook.xls"));

  Sheet sh = wb.getSheetAt(0);
  sh.getRow(0).getCell(0).setCellValue(2);  // set A1=2

  FileOutputStream out = new FileOutputStream("workbook2.xls");
  wb.write(out);
  out.close();
      

Now open workbook2.xls in Excel and the value in C1 is still 2 while you expected 3. Wrong? No! The point is that Excel caches previously calculated results and you need to trigger recalculation to updated them. It is not an issue when you are creating new workbooks from scratch, but important to remember when you are modifing existing workbooks with formulas. This can be done in two ways:

1. Re-evaluate formuals with POI's FormulaEvaluator:

  Workbook wb = WorkbookFactory.create(new FileInputStream("workbook.xls"));

  Sheet sh = wb.getSheetAt(0);
  sh.getRow(0).getCell(0).setCellValue(2);  // set A1=2

  wb.getCreationHelper().createFormulaEvaluator().evaluateAll();
        

2. Delegate re-calculation to Excel. The application will perform a full recalculation when the workbook is opened:

  Workbook wb = WorkbookFactory.create(new FileInputStream("workbook.xls"));

  Sheet sh = wb.getSheetAt(0);
  sh.getRow(0).getCell(0).setCellValue(2);  // set A1=2

  wb.setForceFormulaRecalculation(true);
        
分享到:
评论

相关推荐

    NPOI教程pdf

    - Formula Evaluation library:支持公式计算。 目前,NPOI的最新版本是1.2beta版,它的功能包括: - 读写OLE2文档。 - 读写Document Summary Information和Summary Information。 - 基于LittleEndian的字节读写。...

    XSSF创建Excel高版本

    7. **Formula Evaluation**: XSSF还支持公式计算。你可以创建含有公式的单元格,并使用`FormulaEvaluator`进行计算。 8. **Writing to File**: 创建完Excel文件后,使用`Workbook.write(OutputStream out)`将工作簿...

    java Excel 依赖包

    8. **Formula Evaluation**: 对于含有公式计算的单元格,POI提供了公式求值器来计算结果。 为了在Java项目中使用Apache POI,你需要将依赖包(如poi-3.8.jar)添加到你的类路径中。如果你使用Maven或Gradle,可以...

    公式解析器:解析和评估以字符串形式给出的数学公式

    公式解析器 Formula Parser是用于解析和评估以字符串形式给出的数学公式的库。 支持: 运算符:+,-,*,/,^ 变量:x,y,z,a,b 小数点为“。”的数字E表示法中的数字常数:pi,e,Inf 功能:sqrt,abs,sin,cos...

    有限元的MATLAB解法.pdf

    - 使用算术运算符组合图形对象,编辑Set formula来定义模型的几何形状。 3. **设置坐标和边界** - 双击几何图形进行坐标设置,例如,对于矩形,可以设定left、bottom、width和height等参数。 - 在“Boundary”...

    XNUMBERS 5.6 - Multi Precision Floating Point Computing and Numerical Methods for EXCEL

    Interpolation with Newton formula. Rootfinder algorithms: Jenkins-Traub, Durand-Kerner-Aberth, Newton Generalized, Laguerre, Siljak, Ruffini. Orthogonal polynomials. Numbers Theory: MCD, MCM, ...

    Bloom(2018)_Data_and_Programs_fortran语言_源码

    Fortran,全称Formula Translation,是一种早期的高级编程语言,特别适合于数值计算和科学计算领域。在这个项目中,Bloom使用Fortran的强大计算能力来处理经济模型和数据分析。 1. **Fortran语言基础** - Fortran...

    Photothermal damage prediction of laser interstitial thermotherapy

    The thermal damage was calculated by finite element method (FEM) using Pennes bio-heat transfer equation and Arrhenius injury integral formula. The numerical results showed that the scattering can ...

    JCalcAPI:流利的 Java API,可更轻松地在 Java 中编写公式和计算

    100KB)* Fast evaluation (converted in postfix notation)* High precision (using BigDecimal)* Includes common math functions and operations* Support for strings and parsing formula* Support for ...

    labview数字信号处理

    - **1D & 2D Evaluation**:一维和二维函数评估。 - **Calculus**:微积分计算。 - **Zeros**:寻找函数零点的方法。 **信号处理与分析** - **Waveform Generation**:波形生成。 - **Waveform Conditioning**:...

    Digital and Analogue Communication Systems 2012.

    General Formula for the PSD of Digital Signals, 433 White-Noise Processes, 435 Measurement of PSD, 436 6–3 DC and RMS Values for Ergodic Random Processes 6–4 Linear Systems 439 Input-Output ...

    fcal:适用于JavaScript和Node.js的广泛的数学表达式评估器库

    :house:Fcaljs是一个适用于JavaScript和Node.js的广泛的数学表达式评估器库。 使用fcal,您可以精确地执行基本的算术百分比运算。 它具有灵活的表达式解析器,具有大量内置单元,函数和常量。 灵感来自特征单位变数...

    基于wifi的室内定位算法

    Workshop on Wireless Network Testbeds, Experimental evaluation and Cllaracterization (WiNTECID), Los Angeles, CA, USA positioning systems was made In the second part was presented the way in which ...

Global site tag (gtag.js) - Google Analytics