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.

BaseFormulaEvaluator.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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.ss.formula;
  16. import java.util.Map;
  17. import org.apache.poi.ss.usermodel.Cell;
  18. import org.apache.poi.ss.usermodel.CellType;
  19. import org.apache.poi.ss.usermodel.CellValue;
  20. import org.apache.poi.ss.usermodel.FormulaEvaluator;
  21. import org.apache.poi.ss.usermodel.RichTextString;
  22. import org.apache.poi.ss.usermodel.Row;
  23. import org.apache.poi.ss.usermodel.Sheet;
  24. import org.apache.poi.ss.usermodel.Workbook;
  25. /**
  26. * Common functionality across file formats for evaluating formula cells.<p/>
  27. */
  28. public abstract class BaseFormulaEvaluator implements FormulaEvaluator, WorkbookEvaluatorProvider {
  29. protected final WorkbookEvaluator _bookEvaluator;
  30. protected BaseFormulaEvaluator(WorkbookEvaluator bookEvaluator) {
  31. this._bookEvaluator = bookEvaluator;
  32. }
  33. /**
  34. * Coordinates several formula evaluators together so that formulas that involve external
  35. * references can be evaluated.
  36. * @param workbookNames the simple file names used to identify the workbooks in formulas
  37. * with external links (for example "MyData.xls" as used in a formula "[MyData.xls]Sheet1!A1")
  38. * @param evaluators all evaluators for the full set of workbooks required by the formulas.
  39. */
  40. public static void setupEnvironment(String[] workbookNames, BaseFormulaEvaluator[] evaluators) {
  41. WorkbookEvaluator[] wbEvals = new WorkbookEvaluator[evaluators.length];
  42. for (int i = 0; i < wbEvals.length; i++) {
  43. wbEvals[i] = evaluators[i]._bookEvaluator;
  44. }
  45. CollaboratingWorkbooksEnvironment.setup(workbookNames, wbEvals);
  46. }
  47. @Override
  48. public void setupReferencedWorkbooks(Map<String, FormulaEvaluator> evaluators) {
  49. CollaboratingWorkbooksEnvironment.setupFormulaEvaluator(evaluators);
  50. }
  51. @Override
  52. public WorkbookEvaluator _getWorkbookEvaluator() {
  53. return _bookEvaluator;
  54. }
  55. /**
  56. * Should be called whenever there are major changes (e.g. moving sheets) to input cells
  57. * in the evaluated workbook. If performance is not critical, a single call to this method
  58. * may be used instead of many specific calls to the notify~ methods.
  59. *
  60. * Failure to call this method after changing cell values will cause incorrect behaviour
  61. * of the evaluate~ methods of this class
  62. */
  63. @Override
  64. public void clearAllCachedResultValues() {
  65. _bookEvaluator.clearAllCachedResultValues();
  66. }
  67. /**
  68. * If cell contains a formula, the formula is evaluated and returned,
  69. * else the CellValue simply copies the appropriate cell value from
  70. * the cell and also its cell type. This method should be preferred over
  71. * evaluateInCell() when the call should not modify the contents of the
  72. * original cell.
  73. *
  74. * @param cell may be <code>null</code> signifying that the cell is not present (or blank)
  75. * @return <code>null</code> if the supplied cell is <code>null</code> or blank
  76. */
  77. @Override
  78. public CellValue evaluate(Cell cell) {
  79. if (cell == null) {
  80. return null;
  81. }
  82. switch (cell.getCellTypeEnum()) {
  83. case BOOLEAN:
  84. return CellValue.valueOf(cell.getBooleanCellValue());
  85. case ERROR:
  86. return CellValue.getError(cell.getErrorCellValue());
  87. case FORMULA:
  88. return evaluateFormulaCellValue(cell);
  89. case NUMERIC:
  90. return new CellValue(cell.getNumericCellValue());
  91. case STRING:
  92. return new CellValue(cell.getRichStringCellValue().getString());
  93. case BLANK:
  94. return null;
  95. default:
  96. throw new IllegalStateException("Bad cell type (" + cell.getCellTypeEnum() + ")");
  97. }
  98. }
  99. /**
  100. * If cell contains formula, it evaluates the formula, and
  101. * puts the formula result back into the cell, in place
  102. * of the old formula.
  103. * Else if cell does not contain formula, this method leaves
  104. * the cell unchanged.
  105. * Note that the same instance of HSSFCell is returned to
  106. * allow chained calls like:
  107. * <pre>
  108. * int evaluatedCellType = evaluator.evaluateInCell(cell).getCellType();
  109. * </pre>
  110. * Be aware that your cell value will be changed to hold the
  111. * result of the formula. If you simply want the formula
  112. * value computed for you, use {@link #evaluateFormulaCellEnum(Cell)}}
  113. * @param cell
  114. * @return the {@code cell} that was passed in, allowing for chained calls
  115. */
  116. @Override
  117. public Cell evaluateInCell(Cell cell) {
  118. if (cell == null) {
  119. return null;
  120. }
  121. Cell result = cell;
  122. if (cell.getCellTypeEnum() == CellType.FORMULA) {
  123. CellValue cv = evaluateFormulaCellValue(cell);
  124. setCellValue(cell, cv);
  125. setCellType(cell, cv); // cell will no longer be a formula cell
  126. }
  127. return result;
  128. }
  129. protected abstract CellValue evaluateFormulaCellValue(Cell cell);
  130. /**
  131. * If cell contains formula, it evaluates the formula, and saves the result of the formula. The
  132. * cell remains as a formula cell. If the cell does not contain formula, this method returns -1
  133. * and leaves the cell unchanged.
  134. *
  135. * Note that the type of the <em>formula result</em> is returned, so you know what kind of
  136. * cached formula result is also stored with the formula.
  137. * <pre>
  138. * int evaluatedCellType = evaluator.evaluateFormulaCell(cell);
  139. * </pre>
  140. * Be aware that your cell will hold both the formula, and the result. If you want the cell
  141. * replaced with the result of the formula, use {@link #evaluateInCell(org.apache.poi.ss.usermodel.Cell)}
  142. * @param cell The cell to evaluate
  143. * @return -1 for non-formula cells, or the type of the <em>formula result</em>
  144. * @deprecated 3.15. Will return a {@link CellType} enum in the future.
  145. */
  146. @Override
  147. public int evaluateFormulaCell(Cell cell) {
  148. return evaluateFormulaCellEnum(cell).getCode();
  149. }
  150. /**
  151. * If cell contains formula, it evaluates the formula,
  152. * and saves the result of the formula. The cell
  153. * remains as a formula cell.
  154. * Else if cell does not contain formula, this method leaves
  155. * the cell unchanged.
  156. * Note that the type of the formula result is returned,
  157. * so you know what kind of value is also stored with
  158. * the formula.
  159. * <pre>
  160. * CellType evaluatedCellType = evaluator.evaluateFormulaCellEnum(cell);
  161. * </pre>
  162. * Be aware that your cell will hold both the formula,
  163. * and the result. If you want the cell replaced with
  164. * the result of the formula, use {@link #evaluate(org.apache.poi.ss.usermodel.Cell)} }
  165. * @param cell The cell to evaluate
  166. * @return The type of the formula result (the cell's type remains as CellType.FORMULA however)
  167. * If cell is not a formula cell, returns {@link CellType#_NONE} rather than throwing an exception.
  168. * @since POI 3.15 beta 3
  169. * @deprecated POI 3.15 beta 3. Will be deleted when we make the CellType enum transition. See bug 59791.
  170. */
  171. @Override
  172. public CellType evaluateFormulaCellEnum(Cell cell) {
  173. if (cell == null || cell.getCellTypeEnum() != CellType.FORMULA) {
  174. return CellType._NONE;
  175. }
  176. CellValue cv = evaluateFormulaCellValue(cell);
  177. // cell remains a formula cell, but the cached value is changed
  178. setCellValue(cell, cv);
  179. return cv.getCellTypeEnum();
  180. }
  181. protected static void setCellType(Cell cell, CellValue cv) {
  182. CellType cellType = cv.getCellTypeEnum();
  183. switch (cellType) {
  184. case BOOLEAN:
  185. case ERROR:
  186. case NUMERIC:
  187. case STRING:
  188. cell.setCellType(cellType);
  189. return;
  190. case BLANK:
  191. // never happens - blanks eventually get translated to zero
  192. throw new IllegalArgumentException("This should never happen. Blanks eventually get translated to zero.");
  193. case FORMULA:
  194. // this will never happen, we have already evaluated the formula
  195. throw new IllegalArgumentException("This should never happen. Formulas should have already been evaluated.");
  196. default:
  197. throw new IllegalStateException("Unexpected cell value type (" + cellType + ")");
  198. }
  199. }
  200. protected abstract RichTextString createRichTextString(String str);
  201. protected void setCellValue(Cell cell, CellValue cv) {
  202. CellType cellType = cv.getCellTypeEnum();
  203. switch (cellType) {
  204. case BOOLEAN:
  205. cell.setCellValue(cv.getBooleanValue());
  206. break;
  207. case ERROR:
  208. cell.setCellErrorValue(cv.getErrorValue());
  209. break;
  210. case NUMERIC:
  211. cell.setCellValue(cv.getNumberValue());
  212. break;
  213. case STRING:
  214. cell.setCellValue(createRichTextString(cv.getStringValue()));
  215. break;
  216. case BLANK:
  217. // never happens - blanks eventually get translated to zero
  218. case FORMULA:
  219. // this will never happen, we have already evaluated the formula
  220. default:
  221. throw new IllegalStateException("Unexpected cell value type (" + cellType + ")");
  222. }
  223. }
  224. /**
  225. * Loops over all cells in all sheets of the supplied
  226. * workbook.
  227. * For cells that contain formulas, their formulas are
  228. * evaluated, and the results are saved. These cells
  229. * remain as formula cells.
  230. * For cells that do not contain formulas, no changes
  231. * are made.
  232. * This is a helpful wrapper around looping over all
  233. * cells, and calling evaluateFormulaCell on each one.
  234. */
  235. public static void evaluateAllFormulaCells(Workbook wb) {
  236. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  237. evaluateAllFormulaCells(wb, evaluator);
  238. }
  239. protected static void evaluateAllFormulaCells(Workbook wb, FormulaEvaluator evaluator) {
  240. for(int i=0; i<wb.getNumberOfSheets(); i++) {
  241. Sheet sheet = wb.getSheetAt(i);
  242. for(Row r : sheet) {
  243. for (Cell c : r) {
  244. if (c.getCellTypeEnum() == CellType.FORMULA) {
  245. evaluator.evaluateFormulaCellEnum(c);
  246. }
  247. }
  248. }
  249. }
  250. }
  251. /** {@inheritDoc} */
  252. @Override
  253. public void setIgnoreMissingWorkbooks(boolean ignore){
  254. _bookEvaluator.setIgnoreMissingWorkbooks(ignore);
  255. }
  256. /** {@inheritDoc} */
  257. @Override
  258. public void setDebugEvaluationOutputForNextEval(boolean value){
  259. _bookEvaluator.setDebugEvaluationOutputForNextEval(value);
  260. }
  261. }