|
@@ -1,10 +1,15 @@
|
|
|
package com.ims.common.utils;
|
|
|
|
|
|
+import com.ims.common.function.IFSFunction;
|
|
|
import org.apache.poi.hssf.usermodel.*;
|
|
|
import org.apache.poi.ss.formula.FormulaParseException;
|
|
|
-import org.apache.poi.ss.usermodel.CellType;
|
|
|
-import org.apache.poi.ss.usermodel.FormulaEvaluator;
|
|
|
+import org.apache.poi.ss.formula.functions.FreeRefFunction;
|
|
|
+import org.apache.poi.ss.formula.udf.AggregatingUDFFinder;
|
|
|
+import org.apache.poi.ss.formula.udf.DefaultUDFFinder;
|
|
|
+import org.apache.poi.ss.formula.udf.UDFFinder;
|
|
|
+import org.apache.poi.ss.usermodel.*;
|
|
|
|
|
|
+import java.io.IOException;
|
|
|
import java.math.BigDecimal;
|
|
|
|
|
|
public class FormulaUtils {
|
|
@@ -25,12 +30,15 @@ public class FormulaUtils {
|
|
|
* @param formula Excel 中的公式,例如:MAX(56-FLOOR(20/6,1),2)
|
|
|
* @return
|
|
|
*/
|
|
|
- public static double caculateFormula(String formula) {
|
|
|
+ public static double caculateFormula1(String formula) {
|
|
|
if(formula.startsWith("=")){
|
|
|
formula =formula.replace("=","");
|
|
|
}
|
|
|
HSSFWorkbook workbook = new HSSFWorkbook();
|
|
|
+ workbook.addToolPack(new AggregatingUDFFinder(new DefaultUDFFinder(new String[]{IFSFunction.FUNCTION_NAME}, new FreeRefFunction[]{new IFSFunction()})));
|
|
|
+
|
|
|
HSSFSheet sheet = workbook.createSheet();
|
|
|
+
|
|
|
row = sheet.createRow(0);
|
|
|
formulaEvaluator = new HSSFFormulaEvaluator(workbook);
|
|
|
|
|
@@ -46,4 +54,45 @@ public class FormulaUtils {
|
|
|
return 0;
|
|
|
}
|
|
|
}
|
|
|
+
|
|
|
+
|
|
|
+ public static double caculateFormula(String formula){
|
|
|
+ Workbook workbook = null;
|
|
|
+ try {
|
|
|
+ workbook = new HSSFWorkbook();
|
|
|
+
|
|
|
+ String[] functionNames = { IFSFunction.FUNCTION_NAME } ;
|
|
|
+ FreeRefFunction[] functionImpls = { new IFSFunction() } ;
|
|
|
+
|
|
|
+ UDFFinder udfs = new DefaultUDFFinder( functionNames, functionImpls ) ;
|
|
|
+ UDFFinder udfToolpack = new AggregatingUDFFinder( udfs ) ;
|
|
|
+
|
|
|
+ workbook.addToolPack(udfToolpack);
|
|
|
+
|
|
|
+ FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
|
|
|
+
|
|
|
+ Sheet sheet = workbook.createSheet();
|
|
|
+ Row row = sheet.createRow(0);
|
|
|
+ Cell cell = row.createCell(0);
|
|
|
+ cell.setCellFormula(formula);
|
|
|
+ cell.setCellType(CellType.FORMULA);
|
|
|
+
|
|
|
+ double value = evaluator.evaluate(cell).getNumberValue() ;
|
|
|
+ return new BigDecimal(value).setScale(2, BigDecimal.ROUND_CEILING).doubleValue();
|
|
|
+ } catch (Exception e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ }finally {
|
|
|
+ try {
|
|
|
+ if(null != workbook){
|
|
|
+ workbook.close();
|
|
|
+ }
|
|
|
+ } catch (IOException e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ return 0.0;
|
|
|
+ }
|
|
|
+
|
|
|
}
|