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 13KB

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