POI读取公式的值

摘要:
Excel中的数据:packagepoi;导入java.io。文件输入流;导入java.io。IO异常;导入java.io。输入流;导入程序.apache.poi.hssf.usermodel。HSSF工作手册;importorg.apache.poi.ss.用户模型。单间牢房进口

excel中的数据:
POI读取公式的值第1张

POI读取公式的值第2张

POI读取公式的值第3张

packagepoi;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStream;
importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
importorg.apache.poi.ss.usermodel.Cell;
importorg.apache.poi.ss.usermodel.CellValue;
importorg.apache.poi.ss.usermodel.FormulaEvaluator;
importorg.apache.poi.ss.usermodel.Row;
importorg.apache.poi.ss.usermodel.Sheet;
public classTestReadFormula {
    private staticFormulaEvaluator evaluator;
    public static void main(String[] args) throwsIOException {
        InputStream is=new FileInputStream("ReadFormula.xls");
        HSSFWorkbook wb=newHSSFWorkbook(is);
        Sheet sheet=wb.getSheetAt(0);
        evaluator=wb.getCreationHelper().createFormulaEvaluator();
        for (int i = 1; i <4; i++) {
            Row  row=sheet.getRow(i);
            for(Cell cell : row) {
                System.out.println(getCellValue(cell));
            }
        }
        wb.close();
    }
    private staticString getCellValue(Cell cell) {
        if (cell==null) {
            return "isNull";
        }
        System.out.println("rowIdx:"+cell.getRowIndex()+",colIdx:"+cell.getColumnIndex());
        String cellValue = null;
        switch(cell.getCellType()) {
        caseCell.CELL_TYPE_STRING:
            System.out.print("STRING :");
            cellValue=cell.getStringCellValue();
            break;
        caseCell.CELL_TYPE_NUMERIC:
            System.out.print("NUMERIC:");
            cellValue=String.valueOf(cell.getNumericCellValue());
            break;
        caseCell.CELL_TYPE_FORMULA:
            System.out.print("FORMULA:");
            cellValue=getCellValue(evaluator.evaluate(cell));
            break;
        default:
            System.out.println("Has Default.");
            break;
        }
        returncellValue;
    }
    private staticString getCellValue(CellValue cell) {
        String cellValue = null;
        switch(cell.getCellType()) {
        caseCell.CELL_TYPE_STRING:
            System.out.print("String :");
            cellValue=cell.getStringValue();
            break;
        caseCell.CELL_TYPE_NUMERIC:
            System.out.print("NUMERIC:");
            cellValue=String.valueOf(cell.getNumberValue());
            break;
        caseCell.CELL_TYPE_FORMULA:
            System.out.print("FORMULA:");
            break;
        default:
            break;
        }
        returncellValue;
    }
}

Output:

rowIdx:1,colIdx:0
STRING :begin
rowIdx:1,colIdx:1
STRING :end
rowIdx:1,colIdx:2
FORMULA:String :beginend
rowIdx:2,colIdx:0
NUMERIC:1.0
rowIdx:2,colIdx:1
NUMERIC:3.0
rowIdx:2,colIdx:2
FORMULA:String :13
rowIdx:3,colIdx:0
NUMERIC:1.0
rowIdx:3,colIdx:1
NUMERIC:3.0
rowIdx:3,colIdx:2
FORMULA:NUMERIC:4.0
Formula Evaluation:

User API How-TO

The following code demonstrates how to use the FormulaEvaluator in the context of other POI excel reading code.

There are several ways in which you can use the FormulaEvalutator API.

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 staticevaluateAllFormulaCellsmethod on the appropriate HSSFFormulaEvaluator or XSSFFormulaEvaluator class.

http://poi.apache.org/spreadsheet/eval.html

免责声明:文章转载自《POI读取公式的值》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Unity 宽度适配 NGUI如何删除通知栏无效图标(重置任务栏通知区域)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

keepalived 配置文件参数详解

global_defs 全局配置vrrpd1. vrrp_script添加一个周期性执行的脚本。脚本的退出状态码会被调用它的所有的VRRP Instance记录。2. vrrp_sync_group将所有相关的VRRP实例定义在一起,作为一个VRRP Group,如果组内的任意一个实例出现问题,都可以实现Failover3. garp_group4. vr...

springJPA 之 QueryDSL(一)

引言不可否认的是 JPA 使用是非常方便的,极简化的配置,只需要使用注解,无需任何 xml 的配置文件,语义简单易懂,但是,以上的一切都建立在单表查询的前提下的,我们可以使用 JPA 默认提供的方法,简单加轻松的完成 CRUD 操作。但是如果涉及到多表动态查询, JPA 的功能就显得有些捉襟见肘了,虽然我们可以使用注解 @Query ,在这个注解中写 SQ...

ORA-00001: unique constraint (string.string) violated 违反唯一约束条件(.)

ORA-00001: unique constraint (string.string) violated ORA-00001:违反唯一约束条件(.) Cause: An UPDATE or INSERT statement attempted to insert a duplicate key. For Trusted Oracle configured...

python图像处理之pyocr

使用pyocr类库进行ocr识别,其中tools为’Tesseract’ #!/usr/bin/env python #coding=utf-8 __author__ = 'zhangdebin' from PIL import Image import sys import pyocr tools = pyocr.get_available_to...

配置之XML--读取XML文件 转存为Key-Value

将XML文件读取 绑定数据至Dictionary Eg: Xml文件 <?xml version="1.0" encoding="utf-8" ?> <LanguageConfig> <Chinese></Chinese> <English>002</English> &...

Springcloud 学习笔记04-Springboot连接数据库

一、打开user-service微服务 启动类右键Run’UserServiceApplication’或者点击右上方启动 2 Springboot连接Mysql数据库 (1)首先我们将需要的包导入,这几个包都是我们稍后要用到的: <dependency> <groupId>mysql<...