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.

TestHSSFFormulaEvaluator.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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 static org.junit.jupiter.api.Assertions.assertEquals;
  17. import static org.junit.jupiter.api.Assertions.assertNotEquals;
  18. import static org.junit.jupiter.api.Assertions.assertThrows;
  19. import static org.junit.jupiter.api.Assertions.fail;
  20. import java.io.IOException;
  21. import org.apache.poi.hssf.HSSFITestDataProvider;
  22. import org.apache.poi.hssf.HSSFTestDataSamples;
  23. import org.apache.poi.hssf.record.NameRecord;
  24. import org.apache.poi.ss.formula.EvaluationCell;
  25. import org.apache.poi.ss.formula.EvaluationListener;
  26. import org.apache.poi.ss.formula.WorkbookEvaluator;
  27. import org.apache.poi.ss.formula.WorkbookEvaluatorTestHelper;
  28. import org.apache.poi.ss.formula.eval.NumberEval;
  29. import org.apache.poi.ss.formula.eval.ValueEval;
  30. import org.apache.poi.ss.usermodel.BaseTestFormulaEvaluator;
  31. import org.apache.poi.ss.usermodel.Cell;
  32. import org.apache.poi.ss.usermodel.CellType;
  33. import org.apache.poi.ss.usermodel.CellValue;
  34. import org.junit.jupiter.api.Test;
  35. public final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator {
  36. public TestHSSFFormulaEvaluator() {
  37. super(HSSFITestDataProvider.instance);
  38. }
  39. /**
  40. * Test that the HSSFFormulaEvaluator can evaluate simple named ranges
  41. * (single cells and rectangular areas)
  42. */
  43. @Test
  44. public void testEvaluateSimple() throws IOException {
  45. HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("testNames.xls");
  46. HSSFSheet sheet = wb.getSheetAt(0);
  47. HSSFCell cell = sheet.getRow(8).getCell(0);
  48. HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
  49. CellValue cv = fe.evaluate(cell);
  50. assertEquals(CellType.NUMERIC, cv.getCellType());
  51. assertEquals(3.72, cv.getNumberValue(), 0.0);
  52. wb.close();
  53. }
  54. /**
  55. * When evaluating defined names, POI has to decide whether it is capable. Currently
  56. * (May2009) POI only supports simple cell and area refs.<br>
  57. * The sample spreadsheet (bugzilla attachment 23508) had a name flagged as 'complex'
  58. * which contained a simple area ref. It is not clear what the 'complex' flag is used
  59. * for but POI should look elsewhere to decide whether it can evaluate the name.
  60. */
  61. @Test
  62. public void testDefinedNameWithComplexFlag_bug47048() throws IOException {
  63. // Mock up a spreadsheet to match the critical details of the sample
  64. HSSFWorkbook wb = new HSSFWorkbook();
  65. HSSFSheet sheet = wb.createSheet("Input");
  66. HSSFName definedName = wb.createName();
  67. definedName.setNameName("Is_Multicar_Vehicle");
  68. definedName.setRefersToFormula("Input!$B$17:$G$17");
  69. // Set up some data and the formula
  70. HSSFRow row17 = sheet.createRow(16);
  71. row17.createCell(0).setCellValue(25.0);
  72. row17.createCell(1).setCellValue(1.33);
  73. row17.createCell(2).setCellValue(4.0);
  74. HSSFRow row = sheet.createRow(0);
  75. HSSFCell cellA1 = row.createCell(0);
  76. cellA1.setCellFormula("SUM(Is_Multicar_Vehicle)");
  77. // Set the complex flag - POI doesn't usually manipulate this flag
  78. NameRecord nameRec = TestHSSFName.getNameRecord(definedName);
  79. nameRec.setOptionFlag((short) 0x10); // 0x10 -> complex
  80. HSSFFormulaEvaluator hsf = new HSSFFormulaEvaluator(wb);
  81. CellValue value;
  82. try {
  83. value = hsf.evaluate(cellA1);
  84. assertEquals(CellType.NUMERIC, value.getCellType());
  85. assertEquals(5.33, value.getNumberValue(), 0.0);
  86. } catch (RuntimeException e) {
  87. if (e.getMessage().equals("Don't know how to evaluate name 'Is_Multicar_Vehicle'")) {
  88. fail("Identified bug 47048a");
  89. }
  90. throw e;
  91. } finally {
  92. wb.close();
  93. }
  94. }
  95. private static final class EvalCountListener extends EvaluationListener {
  96. private int _evalCount;
  97. public EvalCountListener() {
  98. _evalCount = 0;
  99. }
  100. @Override
  101. public void onStartEvaluate(EvaluationCell cell, ICacheEntry entry) {
  102. _evalCount++;
  103. }
  104. public int getEvalCount() {
  105. return _evalCount;
  106. }
  107. }
  108. /**
  109. * The HSSFFormula evaluator performance benefits greatly from caching of intermediate cell values
  110. */
  111. @Test
  112. public void testShortCircuitIfEvaluation() throws IOException {
  113. // Set up a simple IF() formula that has measurable evaluation cost for its operands.
  114. try (HSSFWorkbook wb = new HSSFWorkbook()) {
  115. HSSFSheet sheet = wb.createSheet("Sheet1");
  116. HSSFRow row = sheet.createRow(0);
  117. HSSFCell cellA1 = row.createCell(0);
  118. cellA1.setCellFormula("if(B1,C1,D1+E1+F1)");
  119. // populate cells B1..F1 with simple formulas instead of plain values so we can use
  120. // EvaluationListener to check which parts of the first formula get evaluated
  121. for (int i = 1; i < 6; i++) {
  122. // formulas are just literal constants "1".."5"
  123. row.createCell(i).setCellFormula(String.valueOf(i));
  124. }
  125. EvalCountListener evalListener = new EvalCountListener();
  126. WorkbookEvaluator evaluator = WorkbookEvaluatorTestHelper.createEvaluator(wb, evalListener);
  127. ValueEval ve = evaluator.evaluate(HSSFEvaluationTestHelper.wrapCell(cellA1));
  128. int evalCount = evalListener.getEvalCount();
  129. // Without short-circuit-if evaluation, evaluating cell 'A1' takes 3 extra evaluations (for D1,E1,F1)
  130. assertNotEquals(6, evalCount, "Identifed bug 48195 - Formula evaluator should short-circuit IF() calculations.");
  131. assertEquals(3, evalCount);
  132. assertEquals(2.0, ((NumberEval) ve).getNumberValue(), 0D);
  133. }
  134. }
  135. /**
  136. * Ensures that we can handle NameXPtgs in the formulas
  137. * we parse.
  138. */
  139. @Test
  140. public void testXRefs() throws IOException {
  141. try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("XRefCalc.xls");
  142. HSSFWorkbook wb2 = HSSFTestDataSamples.openSampleWorkbook("XRefCalcData.xls")) {
  143. Cell cell;
  144. // VLookup on a name in another file
  145. cell = wb1.getSheetAt(0).getRow(1).getCell(2);
  146. assertEquals(CellType.FORMULA, cell.getCellType());
  147. assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType());
  148. assertEquals(12.30, cell.getNumericCellValue(), 0.0001);
  149. // WARNING - this is wrong!
  150. // The file name should be showing, but bug #45970 is fixed
  151. // we seem to loose it
  152. assertEquals("VLOOKUP(PART,COSTS,2,FALSE)", cell.getCellFormula());
  153. // Simple reference to a name in another file
  154. cell = wb1.getSheetAt(0).getRow(1).getCell(4);
  155. assertEquals(CellType.FORMULA, cell.getCellType());
  156. assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType());
  157. assertEquals(36.90, cell.getNumericCellValue(), 0.0001);
  158. // TODO Correct this!
  159. // The file name should be shown too, see bug #56742
  160. assertEquals("Cost*Markup_Cost", cell.getCellFormula());
  161. // Evaluate the cells
  162. HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb1);
  163. HSSFFormulaEvaluator.setupEnvironment(
  164. new String[]{"XRefCalc.xls", "XRefCalcData.xls"},
  165. new HSSFFormulaEvaluator[]{
  166. eval,
  167. new HSSFFormulaEvaluator(wb2)
  168. }
  169. );
  170. eval.evaluateFormulaCell(
  171. wb1.getSheetAt(0).getRow(1).getCell(2)
  172. );
  173. eval.evaluateFormulaCell(
  174. wb1.getSheetAt(0).getRow(1).getCell(4)
  175. );
  176. // Re-check VLOOKUP one
  177. cell = wb1.getSheetAt(0).getRow(1).getCell(2);
  178. assertEquals(CellType.FORMULA, cell.getCellType());
  179. assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType());
  180. assertEquals(12.30, cell.getNumericCellValue(), 0.0001);
  181. // Re-check ref one
  182. cell = wb1.getSheetAt(0).getRow(1).getCell(4);
  183. assertEquals(CellType.FORMULA, cell.getCellType());
  184. assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType());
  185. assertEquals(36.90, cell.getNumericCellValue(), 0.0001);
  186. // Add a formula that refers to one of the existing external workbooks
  187. cell = wb1.getSheetAt(0).getRow(1).createCell(40);
  188. cell.setCellFormula("Cost*[XRefCalcData.xls]MarkupSheet!$B$1");
  189. // Check is was stored correctly
  190. assertEquals("Cost*[XRefCalcData.xls]MarkupSheet!$B$1", cell.getCellFormula());
  191. // Check it evaluates correctly
  192. eval.evaluateFormulaCell(cell);
  193. assertEquals(24.60 * 1.8, cell.getNumericCellValue(), 0);
  194. // Try to add a formula for a new external workbook, won't be allowed to start
  195. cell = wb1.getSheetAt(0).getRow(1).createCell(42);
  196. final Cell cell2 = cell;
  197. assertThrows(Exception.class, () -> cell2.setCellFormula("[alt.xls]Sheet0!$A$1"),
  198. "New workbook not linked, shouldn't be able to add");
  199. // Link our new workbook
  200. try (HSSFWorkbook wb3 = new HSSFWorkbook()) {
  201. wb3.createSheet().createRow(0).createCell(0).setCellValue("In another workbook");
  202. assertEquals(2, wb1.linkExternalWorkbook("alt.xls", wb3));
  203. // Now add a formula that refers to our new workbook
  204. cell.setCellFormula("[alt.xls]Sheet0!$A$1");
  205. assertEquals("[alt.xls]Sheet0!$A$1", cell.getCellFormula());
  206. HSSFFormulaEvaluator eval2 = eval;
  207. assertThrows(Exception.class, () -> eval2.evaluate(cell2),
  208. "No cached value and no link to workbook, shouldn't evaluate");
  209. // Add a link, check it does
  210. HSSFFormulaEvaluator.setupEnvironment(
  211. new String[]{"XRefCalc.xls", "XRefCalcData.xls", "alt.xls"},
  212. new HSSFFormulaEvaluator[]{
  213. eval,
  214. new HSSFFormulaEvaluator(wb2),
  215. new HSSFFormulaEvaluator(wb3)
  216. }
  217. );
  218. eval.evaluateFormulaCell(cell);
  219. assertEquals("In another workbook", cell.getStringCellValue());
  220. // Save and re-load
  221. try (HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) {
  222. eval = new HSSFFormulaEvaluator(wb4);
  223. HSSFFormulaEvaluator.setupEnvironment(
  224. new String[]{"XRefCalc.xls", "XRefCalcData.xls", "alt.xls"},
  225. new HSSFFormulaEvaluator[]{
  226. eval,
  227. new HSSFFormulaEvaluator(wb2),
  228. new HSSFFormulaEvaluator(wb3)
  229. }
  230. );
  231. // Check the one referring to the previously existing workbook behaves
  232. cell = wb4.getSheetAt(0).getRow(1).getCell(40);
  233. assertEquals("Cost*[XRefCalcData.xls]MarkupSheet!$B$1", cell.getCellFormula());
  234. eval.evaluateFormulaCell(cell);
  235. assertEquals(24.60 * 1.8, cell.getNumericCellValue(), 0);
  236. // Now check the newly added reference
  237. cell = wb4.getSheetAt(0).getRow(1).getCell(42);
  238. assertEquals("[alt.xls]Sheet0!$A$1", cell.getCellFormula());
  239. eval.evaluateFormulaCell(cell);
  240. assertEquals("In another workbook", cell.getStringCellValue());
  241. }
  242. }
  243. }
  244. }
  245. }