You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

HSSFFormulaEvaluator.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.hssf.usermodel;
  16. import java.util.Iterator;
  17. import org.apache.poi.hssf.record.formula.eval.BoolEval;
  18. import org.apache.poi.hssf.record.formula.eval.ErrorEval;
  19. import org.apache.poi.hssf.record.formula.eval.NumberEval;
  20. import org.apache.poi.hssf.record.formula.eval.StringEval;
  21. import org.apache.poi.hssf.record.formula.eval.ValueEval;
  22. import org.apache.poi.hssf.record.formula.udf.UDFFinder;
  23. import org.apache.poi.ss.formula.CollaboratingWorkbooksEnvironment;
  24. import org.apache.poi.ss.formula.IStabilityClassifier;
  25. import org.apache.poi.ss.formula.WorkbookEvaluator;
  26. import org.apache.poi.ss.usermodel.Cell;
  27. import org.apache.poi.ss.usermodel.CellValue;
  28. import org.apache.poi.ss.usermodel.FormulaEvaluator;
  29. import org.apache.poi.ss.usermodel.Row;
  30. /**
  31. * Evaluates formula cells.<p/>
  32. *
  33. * For performance reasons, this class keeps a cache of all previously calculated intermediate
  34. * cell values. Be sure to call {@link #clearAllCachedResultValues()} if any workbook cells are changed between
  35. * calls to evaluate~ methods on this class.
  36. *
  37. * @author Amol S. Deshmukh &lt; amolweb at ya hoo dot com &gt;
  38. * @author Josh Micich
  39. */
  40. public class HSSFFormulaEvaluator implements FormulaEvaluator {
  41. private WorkbookEvaluator _bookEvaluator;
  42. /**
  43. * @deprecated (Sep 2008) HSSFSheet parameter is ignored
  44. */
  45. public HSSFFormulaEvaluator(HSSFSheet sheet, HSSFWorkbook workbook) {
  46. this(workbook);
  47. if (false) {
  48. sheet.toString(); // suppress unused parameter compiler warning
  49. }
  50. }
  51. public HSSFFormulaEvaluator(HSSFWorkbook workbook) {
  52. this(workbook, null);
  53. }
  54. /**
  55. * @param stabilityClassifier used to optimise caching performance. Pass <code>null</code>
  56. * for the (conservative) assumption that any cell may have its definition changed after
  57. * evaluation begins.
  58. */
  59. public HSSFFormulaEvaluator(HSSFWorkbook workbook, IStabilityClassifier stabilityClassifier) {
  60. this(workbook, stabilityClassifier, null);
  61. }
  62. /**
  63. * @param udfFinder pass <code>null</code> for default (AnalysisToolPak only)
  64. */
  65. private HSSFFormulaEvaluator(HSSFWorkbook workbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) {
  66. _bookEvaluator = new WorkbookEvaluator(HSSFEvaluationWorkbook.create(workbook), stabilityClassifier, udfFinder);
  67. }
  68. /**
  69. * @param stabilityClassifier used to optimise caching performance. Pass <code>null</code>
  70. * for the (conservative) assumption that any cell may have its definition changed after
  71. * evaluation begins.
  72. * @param udfFinder pass <code>null</code> for default (AnalysisToolPak only)
  73. */
  74. public static HSSFFormulaEvaluator create(HSSFWorkbook workbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) {
  75. return new HSSFFormulaEvaluator(workbook, stabilityClassifier, udfFinder);
  76. }
  77. /**
  78. * Coordinates several formula evaluators together so that formulas that involve external
  79. * references can be evaluated.
  80. * @param workbookNames the simple file names used to identify the workbooks in formulas
  81. * with external links (for example "MyData.xls" as used in a formula "[MyData.xls]Sheet1!A1")
  82. * @param evaluators all evaluators for the full set of workbooks required by the formulas.
  83. */
  84. public static void setupEnvironment(String[] workbookNames, HSSFFormulaEvaluator[] evaluators) {
  85. WorkbookEvaluator[] wbEvals = new WorkbookEvaluator[evaluators.length];
  86. for (int i = 0; i < wbEvals.length; i++) {
  87. wbEvals[i] = evaluators[i]._bookEvaluator;
  88. }
  89. CollaboratingWorkbooksEnvironment.setup(workbookNames, wbEvals);
  90. }
  91. /**
  92. * Does nothing
  93. * @deprecated (Aug 2008) - not needed, since the current row can be derived from the cell
  94. */
  95. public void setCurrentRow(HSSFRow row) {
  96. // do nothing
  97. if (false) {
  98. row.getClass(); // suppress unused parameter compiler warning
  99. }
  100. }
  101. /**
  102. * Should be called whenever there are major changes (e.g. moving sheets) to input cells
  103. * in the evaluated workbook. If performance is not critical, a single call to this method
  104. * may be used instead of many specific calls to the notify~ methods.
  105. *
  106. * Failure to call this method after changing cell values will cause incorrect behaviour
  107. * of the evaluate~ methods of this class
  108. */
  109. public void clearAllCachedResultValues() {
  110. _bookEvaluator.clearAllCachedResultValues();
  111. }
  112. /**
  113. * Should be called to tell the cell value cache that the specified (value or formula) cell
  114. * has changed.
  115. * Failure to call this method after changing cell values will cause incorrect behaviour
  116. * of the evaluate~ methods of this class
  117. */
  118. public void notifyUpdateCell(HSSFCell cell) {
  119. _bookEvaluator.notifyUpdateCell(new HSSFEvaluationCell(cell));
  120. }
  121. public void notifyUpdateCell(Cell cell) {
  122. _bookEvaluator.notifyUpdateCell(new HSSFEvaluationCell((HSSFCell)cell));
  123. }
  124. /**
  125. * Should be called to tell the cell value cache that the specified cell has just been
  126. * deleted.
  127. * Failure to call this method after changing cell values will cause incorrect behaviour
  128. * of the evaluate~ methods of this class
  129. */
  130. public void notifyDeleteCell(HSSFCell cell) {
  131. _bookEvaluator.notifyDeleteCell(new HSSFEvaluationCell(cell));
  132. }
  133. public void notifyDeleteCell(Cell cell) {
  134. _bookEvaluator.notifyDeleteCell(new HSSFEvaluationCell((HSSFCell)cell));
  135. }
  136. /**
  137. * Should be called to tell the cell value cache that the specified (value or formula) cell
  138. * has changed.
  139. * Failure to call this method after changing cell values will cause incorrect behaviour
  140. * of the evaluate~ methods of this class
  141. */
  142. public void notifySetFormula(Cell cell) {
  143. _bookEvaluator.notifyUpdateCell(new HSSFEvaluationCell((HSSFCell)cell));
  144. }
  145. /**
  146. * If cell contains a formula, the formula is evaluated and returned,
  147. * else the CellValue simply copies the appropriate cell value from
  148. * the cell and also its cell type. This method should be preferred over
  149. * evaluateInCell() when the call should not modify the contents of the
  150. * original cell.
  151. *
  152. * @param cell may be <code>null</code> signifying that the cell is not present (or blank)
  153. * @return <code>null</code> if the supplied cell is <code>null</code> or blank
  154. */
  155. public CellValue evaluate(Cell cell) {
  156. if (cell == null) {
  157. return null;
  158. }
  159. switch (cell.getCellType()) {
  160. case HSSFCell.CELL_TYPE_BOOLEAN:
  161. return CellValue.valueOf(cell.getBooleanCellValue());
  162. case HSSFCell.CELL_TYPE_ERROR:
  163. return CellValue.getError(cell.getErrorCellValue());
  164. case HSSFCell.CELL_TYPE_FORMULA:
  165. return evaluateFormulaCellValue(cell);
  166. case HSSFCell.CELL_TYPE_NUMERIC:
  167. return new CellValue(cell.getNumericCellValue());
  168. case HSSFCell.CELL_TYPE_STRING:
  169. return new CellValue(cell.getRichStringCellValue().getString());
  170. case HSSFCell.CELL_TYPE_BLANK:
  171. return null;
  172. }
  173. throw new IllegalStateException("Bad cell type (" + cell.getCellType() + ")");
  174. }
  175. /**
  176. * If cell contains formula, it evaluates the formula, and saves the result of the formula. The
  177. * cell remains as a formula cell. If the cell does not contain formula, this method returns -1
  178. * and leaves the cell unchanged.
  179. *
  180. * Note that the type of the <em>formula result</em> is returned, so you know what kind of
  181. * cached formula result is also stored with the formula.
  182. * <pre>
  183. * int evaluatedCellType = evaluator.evaluateFormulaCell(cell);
  184. * </pre>
  185. * Be aware that your cell will hold both the formula, and the result. If you want the cell
  186. * replaced with the result of the formula, use {@link #evaluateInCell(org.apache.poi.ss.usermodel.Cell)}
  187. * @param cell The cell to evaluate
  188. * @return -1 for non-formula cells, or the type of the <em>formula result</em>
  189. */
  190. public int evaluateFormulaCell(Cell cell) {
  191. if (cell == null || cell.getCellType() != HSSFCell.CELL_TYPE_FORMULA) {
  192. return -1;
  193. }
  194. CellValue cv = evaluateFormulaCellValue(cell);
  195. // cell remains a formula cell, but the cached value is changed
  196. setCellValue(cell, cv);
  197. return cv.getCellType();
  198. }
  199. /**
  200. * If cell contains formula, it evaluates the formula, and
  201. * puts the formula result back into the cell, in place
  202. * of the old formula.
  203. * Else if cell does not contain formula, this method leaves
  204. * the cell unchanged.
  205. * Note that the same instance of HSSFCell is returned to
  206. * allow chained calls like:
  207. * <pre>
  208. * int evaluatedCellType = evaluator.evaluateInCell(cell).getCellType();
  209. * </pre>
  210. * Be aware that your cell value will be changed to hold the
  211. * result of the formula. If you simply want the formula
  212. * value computed for you, use {@link #evaluateFormulaCell(Cell)}}
  213. */
  214. public HSSFCell evaluateInCell(Cell cell) {
  215. if (cell == null) {
  216. return null;
  217. }
  218. HSSFCell result = (HSSFCell) cell;
  219. if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
  220. CellValue cv = evaluateFormulaCellValue(cell);
  221. setCellValue(cell, cv);
  222. setCellType(cell, cv); // cell will no longer be a formula cell
  223. }
  224. return result;
  225. }
  226. private static void setCellType(Cell cell, CellValue cv) {
  227. int cellType = cv.getCellType();
  228. switch (cellType) {
  229. case HSSFCell.CELL_TYPE_BOOLEAN:
  230. case HSSFCell.CELL_TYPE_ERROR:
  231. case HSSFCell.CELL_TYPE_NUMERIC:
  232. case HSSFCell.CELL_TYPE_STRING:
  233. cell.setCellType(cellType);
  234. return;
  235. case HSSFCell.CELL_TYPE_BLANK:
  236. // never happens - blanks eventually get translated to zero
  237. case HSSFCell.CELL_TYPE_FORMULA:
  238. // this will never happen, we have already evaluated the formula
  239. }
  240. throw new IllegalStateException("Unexpected cell value type (" + cellType + ")");
  241. }
  242. private static void setCellValue(Cell cell, CellValue cv) {
  243. int cellType = cv.getCellType();
  244. switch (cellType) {
  245. case HSSFCell.CELL_TYPE_BOOLEAN:
  246. cell.setCellValue(cv.getBooleanValue());
  247. break;
  248. case HSSFCell.CELL_TYPE_ERROR:
  249. cell.setCellErrorValue(cv.getErrorValue());
  250. break;
  251. case HSSFCell.CELL_TYPE_NUMERIC:
  252. cell.setCellValue(cv.getNumberValue());
  253. break;
  254. case HSSFCell.CELL_TYPE_STRING:
  255. cell.setCellValue(new HSSFRichTextString(cv.getStringValue()));
  256. break;
  257. case HSSFCell.CELL_TYPE_BLANK:
  258. // never happens - blanks eventually get translated to zero
  259. case HSSFCell.CELL_TYPE_FORMULA:
  260. // this will never happen, we have already evaluated the formula
  261. default:
  262. throw new IllegalStateException("Unexpected cell value type (" + cellType + ")");
  263. }
  264. }
  265. /**
  266. * Loops over all cells in all sheets of the supplied
  267. * workbook.
  268. * For cells that contain formulas, their formulas are
  269. * evaluated, and the results are saved. These cells
  270. * remain as formula cells.
  271. * For cells that do not contain formulas, no changes
  272. * are made.
  273. * This is a helpful wrapper around looping over all
  274. * cells, and calling evaluateFormulaCell on each one.
  275. */
  276. public static void evaluateAllFormulaCells(HSSFWorkbook wb) {
  277. HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb);
  278. for(int i=0; i<wb.getNumberOfSheets(); i++) {
  279. HSSFSheet sheet = wb.getSheetAt(i);
  280. for (Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();) {
  281. Row r = rit.next();
  282. for (Iterator<Cell> cit = r.cellIterator(); cit.hasNext();) {
  283. Cell c = cit.next();
  284. if (c.getCellType() == HSSFCell.CELL_TYPE_FORMULA)
  285. evaluator.evaluateFormulaCell(c);
  286. }
  287. }
  288. }
  289. }
  290. /**
  291. * Returns a CellValue wrapper around the supplied ValueEval instance.
  292. * @param eval
  293. */
  294. private CellValue evaluateFormulaCellValue(Cell cell) {
  295. ValueEval eval = _bookEvaluator.evaluate(new HSSFEvaluationCell((HSSFCell)cell));
  296. if (eval instanceof NumberEval) {
  297. NumberEval ne = (NumberEval) eval;
  298. return new CellValue(ne.getNumberValue());
  299. }
  300. if (eval instanceof BoolEval) {
  301. BoolEval be = (BoolEval) eval;
  302. return CellValue.valueOf(be.getBooleanValue());
  303. }
  304. if (eval instanceof StringEval) {
  305. StringEval ne = (StringEval) eval;
  306. return new CellValue(ne.getStringValue());
  307. }
  308. if (eval instanceof ErrorEval) {
  309. return CellValue.getError(((ErrorEval)eval).getErrorCode());
  310. }
  311. throw new RuntimeException("Unexpected eval class (" + eval.getClass().getName() + ")");
  312. }
  313. }