POI读取公式的值

简介: excel中的数据:   package poi; import java.io.FileInputStream; import java.io.IOException; import java.

excel中的数据:

 

package poi;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

public class TestReadFormula {
    private static FormulaEvaluator evaluator;
    public static void main(String[] args) throws IOException {
        InputStream is=new FileInputStream("ReadFormula.xls");
        HSSFWorkbook wb=new HSSFWorkbook(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 static String getCellValue(Cell cell) {
        if (cell==null) {
            return "isNull";
        }
        System.out.println("rowIdx:"+cell.getRowIndex()+",colIdx:"+cell.getColumnIndex());
        String cellValue = null;
        switch (cell.getCellType()) {
        case Cell.CELL_TYPE_STRING:
            System.out.print("STRING :");
            cellValue=cell.getStringCellValue();
            break;

        case Cell.CELL_TYPE_NUMERIC:
            System.out.print("NUMERIC:");
            cellValue=String.valueOf(cell.getNumericCellValue());
            break;
            
        case Cell.CELL_TYPE_FORMULA:
            System.out.print("FORMULA:");
            cellValue=getCellValue(evaluator.evaluate(cell));
            break;
        default:
            System.out.println("Has Default.");
            break;
        }
        
        return cellValue;
    }

    private static String getCellValue(CellValue cell) {
        String cellValue = null;
        switch (cell.getCellType()) {
        case Cell.CELL_TYPE_STRING:
            System.out.print("String :");
            cellValue=cell.getStringValue();
            break;

        case Cell.CELL_TYPE_NUMERIC:
            System.out.print("NUMERIC:");
            cellValue=String.valueOf(cell.getNumberValue());
            break;
        case Cell.CELL_TYPE_FORMULA:
            System.out.print("FORMULA:");
            break;
        default:
            break;
        }
        
        return cellValue;
    }

}

 

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

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

 

目录
相关文章
|
负载均衡 Kubernetes API
Istio:Gateway设计与实现
Istio:Gateway设计与实现
Istio:Gateway设计与实现
|
JavaScript 前端开发
JavaScript:解决计算精度问题/mathjs/bignumber.js/big.js/decimal.js
JavaScript:解决计算精度问题/mathjs/bignumber.js/big.js/decimal.js
2462 0
|
11月前
|
云安全 弹性计算 安全
阿里云服务器安全功能解析:基础防护与云安全产品参考
在使用云服务器的过程中,云服务器的安全问题是很多用户非常关心的问题。阿里云服务器除了提供基础的防护之外,还提供了一系列安全防护类云产品,以确保用户云服务器的安全。本文将详细介绍阿里云服务器的基础安全防护有哪些,以及阿里云的一些安全防护类云产品,帮助用户更好地理解和使用阿里云服务器的安全功能。
|
安全 搜索推荐 数据挖掘
淘宝API接口介绍:助你高效开展电商业务
淘宝API接口是连接淘宝平台与外部应用的桥梁,提供商品管理、订单处理、用户分析等多功能服务。它以丰富的数据资源、实时性和高安全性著称,支持电商平台搭建、商品推荐优化及市场分析等场景。未来,淘宝API将融合AI、大数据等技术,拓展生态合作,并强化安全合规性,为电商发展注入新动力。
|
存储 负载均衡 安全
中间件消息发布-订阅模式
【6月更文挑战第9天】
552 5
|
消息中间件 数据安全/隐私保护 RocketMQ
消息队列 MQ使用问题之遇到消费速度是固定的并且导致了堆积,该怎么办
消息队列(MQ)是一种用于异步通信和解耦的应用程序间消息传递的服务,广泛应用于分布式系统中。针对不同的MQ产品,如阿里云的RocketMQ、RabbitMQ等,它们在实现上述场景时可能会有不同的特性和优势,比如RocketMQ强调高吞吐量、低延迟和高可用性,适合大规模分布式系统;而RabbitMQ则以其灵活的路由规则和丰富的协议支持受到青睐。下面是一些常见的消息队列MQ产品的使用场景合集,这些场景涵盖了多种行业和业务需求。
|
JSON 网络协议 Ubuntu
Wireshark网络分析工具
Wireshark网络分析工具
|
JavaScript 前端开发
vue3定时器
vue3定时器
1244 0
|
Cloud Native API 数据安全/隐私保护
【云原生之Docker实战】使用Docker部署ShowDoc文档工具
【云原生之Docker实战】使用Docker部署ShowDoc文档工具
974 2
【云原生之Docker实战】使用Docker部署ShowDoc文档工具
|
JSON NoSQL Java
Redis键值:\xac\xed\x00\x05t\x00的解决
Redis键值:\xac\xed\x00\x05t\x00的解决
1043 0

热门文章

最新文章