How to use org.apache.poi.ss.formula.FormulaParser to parse the formula?

只愿长相守 提交于 2019-12-11 13:07:47

问题


Can u give me the simple code snippt using org.apache.poi.ss.formula.FormulaParser.

FormulaParser class having the method parse().But it returns ptg[].i dont know where is the ptg class...
Please guide me to use formulaParse to parse the excel sheet formula...

Saravanan


回答1:


Ptg[] is a array of tokens which represents the formula in the cell.

Suppose in my excel sheet I have as cell with a formula as

=D4+D6+D8-D11+D23+D29+D46-D49

Running this through a FormulaParser gives me an array which I have printed out as shown below

HSSFEvaluationWorkbook hssfew = HSSFEvaluationWorkbook.create(workBook);

Ptg[] ptg = FormulaParser.parse(cell1.getCellFormula(), hssfew, FormulaType.NAMEDRANGE, 0);

for (int i=0;i<ptg.length;i++){
    System.out.println (ptg[i]);
}

Result

org.apache.poi.hssf.record.formula.RefPtg [D4] 
org.apache.poi.hssf.record.formula.RefPtg [D6] 
class org.apache.poi.hssf.record.formula.AddPtg 
org.apache.poi.hssf.record.formula.RefPtg [D8] 
class org.apache.poi.hssf.record.formula.AddPtg 
org.apache.poi.hssf.record.formula.RefPtg [D11] 
class org.apache.poi.hssf.record.formula.SubtractPtg
org.apache.poi.hssf.record.formula.RefPtg [D23]
class org.apache.poi.hssf.record.formula.AddPtg 
org.apache.poi.hssf.record.formula.RefPtg [D29] 
class org.apache.poi.hssf.record.formula.AddPtg 
org.apache.poi.hssf.record.formula.RefPtg [D46] 
class org.apache.poi.hssf.record.formula.AddPtg 
org.apache.poi.hssf.record.formula.RefPtg [D49] 
class org.apache.poi.hssf.record.formula.SubtractPtg

As you can see this breaks down each element in the formula into the respective cell location or operator AddPtg for + and SubtractPtg for - operator

This is a simple example, you can try out more complex stuff



来源:https://stackoverflow.com/questions/4273871/how-to-use-org-apache-poi-ss-formula-formulaparser-to-parse-the-formula

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!