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.

TestXSSFFormulaEvaluation.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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.xssf.usermodel;
  16. import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
  17. import static org.junit.jupiter.api.Assertions.assertEquals;
  18. import static org.junit.jupiter.api.Assertions.assertNotNull;
  19. import static org.junit.jupiter.api.Assertions.assertSame;
  20. import static org.junit.jupiter.api.Assertions.assertThrows;
  21. import java.io.IOException;
  22. import java.util.HashMap;
  23. import java.util.Map;
  24. import java.util.function.Function;
  25. import org.apache.poi.hssf.HSSFTestDataSamples;
  26. import org.apache.poi.ss.usermodel.BaseTestFormulaEvaluator;
  27. import org.apache.poi.ss.usermodel.Cell;
  28. import org.apache.poi.ss.usermodel.CellValue;
  29. import org.apache.poi.ss.usermodel.FormulaEvaluator;
  30. import org.apache.poi.ss.usermodel.Row;
  31. import org.apache.poi.ss.usermodel.Sheet;
  32. import org.apache.poi.ss.usermodel.Workbook;
  33. import org.apache.poi.ss.util.CellReference;
  34. import org.apache.poi.xssf.XSSFITestDataProvider;
  35. import org.apache.poi.xssf.XSSFTestDataSamples;
  36. import org.junit.jupiter.api.Disabled;
  37. import org.junit.jupiter.api.Test;
  38. import org.junit.jupiter.params.ParameterizedTest;
  39. import org.junit.jupiter.params.provider.ValueSource;
  40. public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
  41. public TestXSSFFormulaEvaluation() {
  42. super(XSSFITestDataProvider.instance);
  43. }
  44. @Test
  45. public void testSharedFormulas_evaluateInCell() throws IOException {
  46. try (Workbook wb = _testDataProvider.openSampleWorkbook("49872.xlsx")) {
  47. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  48. Sheet sheet = wb.getSheetAt(0);
  49. double result = 3.0;
  50. // B3 is a master shared formula, C3 and D3 don't have the formula written in their f element.
  51. // Instead, the attribute si for a particular cell is used to figure what the formula expression
  52. // should be based on the cell's relative location to the master formula, e.g.
  53. // B3: <f t="shared" ref="B3:D3" si="0">B1+B2</f>
  54. // C3 and D3: <f t="shared" si="0"/>
  55. // get B3 and evaluate it in the cell
  56. Cell b3 = sheet.getRow(2).getCell(1);
  57. assertEquals(result, evaluator.evaluateInCell(b3).getNumericCellValue(), 0);
  58. //at this point the master formula is gone, but we are still able to evaluate dependent cells
  59. Cell c3 = sheet.getRow(2).getCell(2);
  60. assertEquals(result, evaluator.evaluateInCell(c3).getNumericCellValue(), 0);
  61. Cell d3 = sheet.getRow(2).getCell(3);
  62. assertEquals(result, evaluator.evaluateInCell(d3).getNumericCellValue(), 0);
  63. }
  64. }
  65. /**
  66. * Evaluation of cell references with column indexes greater than 255. See bugzilla 50096
  67. */
  68. @Test
  69. public void testEvaluateColumnGreaterThan255() throws IOException {
  70. try (Workbook wb = _testDataProvider.openSampleWorkbook("50096.xlsx")) {
  71. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  72. /*
  73. * The first row simply contains the numbers 1 - 300.
  74. * The second row simply refers to the cell value above in the first row by a simple formula.
  75. */
  76. for (int i = 245; i < 265; i++) {
  77. Cell cell_noformula = wb.getSheetAt(0).getRow(0).getCell(i);
  78. Cell cell_formula = wb.getSheetAt(0).getRow(1).getCell(i);
  79. CellReference ref_noformula = new CellReference(cell_noformula.getRowIndex(), cell_noformula.getColumnIndex());
  80. CellReference ref_formula = new CellReference(cell_noformula.getRowIndex(), cell_noformula.getColumnIndex());
  81. String fmla = cell_formula.getCellFormula();
  82. // assure that the formula refers to the cell above.
  83. // the check below is 'deep' and involves conversion of the shared formula:
  84. // in the sample file a shared formula in GN1 is spanned in the range GN2:IY2,
  85. assertEquals(ref_noformula.formatAsString(), fmla);
  86. CellValue cv_noformula = evaluator.evaluate(cell_noformula);
  87. CellValue cv_formula = evaluator.evaluate(cell_formula);
  88. assertEquals(cv_noformula.getNumberValue(), cv_formula.getNumberValue(), 0,
  89. "Wrong evaluation result in " + ref_formula.formatAsString());
  90. }
  91. }
  92. }
  93. /**
  94. * Related to bugs #56737 and #56752 - XSSF workbooks which have
  95. * formulas that refer to cells and named ranges in multiple other
  96. * workbooks, both HSSF and XSSF ones
  97. */
  98. @Test
  99. public void testReferencesToOtherWorkbooks() throws Exception {
  100. try (Workbook wb = _testDataProvider.openSampleWorkbook("ref2-56737.xlsx")) {
  101. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  102. Sheet s = wb.getSheetAt(0);
  103. // References to a .xlsx file
  104. Row rXSLX = s.getRow(2);
  105. Cell cXSLX_cell = rXSLX.getCell(4);
  106. Cell cXSLX_sNR = rXSLX.getCell(6);
  107. Cell cXSLX_gNR = rXSLX.getCell(8);
  108. assertEquals("[1]Uses!$A$1", cXSLX_cell.getCellFormula());
  109. assertEquals("[1]Defines!NR_To_A1", cXSLX_sNR.getCellFormula());
  110. assertEquals("[1]!NR_Global_B2", cXSLX_gNR.getCellFormula());
  111. assertEquals("Hello!", cXSLX_cell.getStringCellValue());
  112. assertEquals("Test A1", cXSLX_sNR.getStringCellValue());
  113. assertEquals(142.0, cXSLX_gNR.getNumericCellValue(), 0);
  114. // References to a .xls file
  115. Row rXSL = s.getRow(4);
  116. Cell cXSL_cell = rXSL.getCell(4);
  117. Cell cXSL_sNR = rXSL.getCell(6);
  118. Cell cXSL_gNR = rXSL.getCell(8);
  119. assertEquals("[2]Uses!$C$1", cXSL_cell.getCellFormula());
  120. assertEquals("[2]Defines!NR_To_A1", cXSL_sNR.getCellFormula());
  121. assertEquals("[2]!NR_Global_B2", cXSL_gNR.getCellFormula());
  122. assertEquals("Hello!", cXSL_cell.getStringCellValue());
  123. assertEquals("Test A1", cXSL_sNR.getStringCellValue());
  124. assertEquals(142.0, cXSL_gNR.getNumericCellValue(), 0);
  125. // Try to evaluate without references, won't work
  126. // (At least, not unit we fix bug #56752 that is)
  127. assertThrows(Exception.class, () -> evaluator.evaluate(cXSL_cell),
  128. "Without a fix for #56752, shouldn't be able to evaluate a reference to a non-provided linked workbook");
  129. // Setup the environment
  130. Map<String, FormulaEvaluator> evaluators = new HashMap<>();
  131. evaluators.put("ref2-56737.xlsx", evaluator);
  132. try (Workbook wbEval1 = _testDataProvider.openSampleWorkbook("56737.xlsx");
  133. Workbook wbEval2 = HSSFTestDataSamples.openSampleWorkbook("56737.xls")) {
  134. evaluators.put("56737.xlsx", wbEval1.getCreationHelper().createFormulaEvaluator());
  135. evaluators.put("56737.xls", wbEval2.getCreationHelper().createFormulaEvaluator());
  136. evaluator.setupReferencedWorkbooks(evaluators);
  137. // Try evaluating all of them, ensure we don't blow up
  138. for (Row r : s) {
  139. for (Cell c : r) {
  140. evaluator.evaluate(c);
  141. }
  142. }
  143. // And evaluate the other way too
  144. evaluator.evaluateAll();
  145. // Static evaluator won't work, as no references passed in
  146. assertThrows(Exception.class, () -> XSSFFormulaEvaluator.evaluateAllFormulaCells(wb),
  147. "Static method lacks references, shouldn't work");
  148. // Evaluate specific cells and check results
  149. assertEquals("\"Hello!\"", evaluator.evaluate(cXSLX_cell).formatAsString());
  150. assertEquals("\"Test A1\"", evaluator.evaluate(cXSLX_sNR).formatAsString());
  151. assertEquals("142.0", evaluator.evaluate(cXSLX_gNR).formatAsString());
  152. assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell).formatAsString());
  153. assertEquals("\"Test A1\"", evaluator.evaluate(cXSL_sNR).formatAsString());
  154. assertEquals("142.0", evaluator.evaluate(cXSL_gNR).formatAsString());
  155. // Add another formula referencing these workbooks
  156. Cell cXSL_cell2 = rXSL.createCell(40);
  157. cXSL_cell2.setCellFormula("[56737.xls]Uses!$C$1");
  158. // TODO Shouldn't it become [2] like the others?
  159. assertEquals("[56737.xls]Uses!$C$1", cXSL_cell2.getCellFormula());
  160. assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell2).formatAsString());
  161. // Now add a formula that refers to yet another (different) workbook
  162. // Won't work without the workbook being linked
  163. Cell cXSLX_nw_cell = rXSLX.createCell(42);
  164. assertThrows(Exception.class, () -> cXSLX_nw_cell.setCellFormula("[alt.xlsx]Sheet1!$A$1"),
  165. "New workbook not linked, shouldn't be able to add");
  166. }
  167. // Link and re-try
  168. try (Workbook alt = new XSSFWorkbook()) {
  169. alt.createSheet().createRow(0).createCell(0).setCellValue("In another workbook");
  170. // TODO Implement the rest of this, see bug #57184
  171. /*
  172. wb.linkExternalWorkbook("alt.xlsx", alt);
  173. cXSLX_nw_cell.setCellFormula("[alt.xlsx]Sheet1!$A$1");
  174. // Check it - TODO Is this correct? Or should it become [3]Sheet1!$A$1 ?
  175. assertEquals("[alt.xlsx]Sheet1!$A$1", cXSLX_nw_cell.getCellFormula());
  176. // Evaluate it, without a link to that workbook
  177. assertThrows(Exception.class, () -> evaluator.evaluate(cXSLX_nw_cell),
  178. "No cached value and no link to workbook, shouldn't evaluate");
  179. // Add a link, check it does
  180. evaluators.put("alt.xlsx", alt.getCreationHelper().createFormulaEvaluator());
  181. evaluator.setupReferencedWorkbooks(evaluators);
  182. evaluator.evaluate(cXSLX_nw_cell);
  183. assertEquals("In another workbook", cXSLX_nw_cell.getStringCellValue());
  184. */
  185. }
  186. }
  187. }
  188. /*
  189. * If a formula references cells or named ranges in another workbook,
  190. * but that isn't available at evaluation time, the cached values
  191. * should be used instead
  192. * TODO Add the support then add a unit test
  193. * See bug #56752
  194. */
  195. // @Disabled
  196. // public void testCachedReferencesToOtherWorkbooks() {
  197. // }
  198. /**
  199. * A handful of functions (such as SUM, COUNTA, MIN) support
  200. * multi-sheet references (eg Sheet1:Sheet3!A1 = Cell A1 from
  201. * Sheets 1 through Sheet 3).
  202. * This test, based on common test files for HSSF and XSSF, checks
  203. * that we can correctly evaluate these
  204. */
  205. @ParameterizedTest
  206. @ValueSource(strings = {"55906-MultiSheetRefs.xls","55906-MultiSheetRefs.xlsx"})
  207. public void testMultiSheetReferencesHSSFandXSSF(String sampleFileName) throws Exception {
  208. Function<String, Workbook> fun = sampleFileName.endsWith("x")
  209. ? XSSFTestDataSamples::openSampleWorkbook : HSSFTestDataSamples::openSampleWorkbook;
  210. try (Workbook wb = fun.apply(sampleFileName)) {
  211. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  212. Sheet s1 = wb.getSheetAt(0);
  213. // Simple SUM over numbers
  214. Cell sumF = s1.getRow(2).getCell(0);
  215. assertNotNull(sumF);
  216. assertEquals("SUM(Sheet1:Sheet3!A1)", sumF.getCellFormula());
  217. assertEquals("66.0", evaluator.evaluate(sumF).formatAsString(), "Failed for " + wb.getClass());
  218. // Various Stats formulas on numbers
  219. Cell avgF = s1.getRow(2).getCell(1);
  220. assertNotNull(avgF);
  221. assertEquals("AVERAGE(Sheet1:Sheet3!A1)", avgF.getCellFormula());
  222. assertEquals("22.0", evaluator.evaluate(avgF).formatAsString());
  223. Cell minF = s1.getRow(3).getCell(1);
  224. assertNotNull(minF);
  225. assertEquals("MIN(Sheet1:Sheet3!A$1)", minF.getCellFormula());
  226. assertEquals("11.0", evaluator.evaluate(minF).formatAsString());
  227. Cell maxF = s1.getRow(4).getCell(1);
  228. assertNotNull(maxF);
  229. assertEquals("MAX(Sheet1:Sheet3!A$1)", maxF.getCellFormula());
  230. assertEquals("33.0", evaluator.evaluate(maxF).formatAsString());
  231. Cell countF = s1.getRow(5).getCell(1);
  232. assertNotNull(countF);
  233. assertEquals("COUNT(Sheet1:Sheet3!A$1)", countF.getCellFormula());
  234. assertEquals("3.0", evaluator.evaluate(countF).formatAsString());
  235. // Various CountAs on Strings
  236. Cell countA_1F = s1.getRow(2).getCell(2);
  237. assertNotNull(countA_1F);
  238. assertEquals("COUNTA(Sheet1:Sheet3!C1)", countA_1F.getCellFormula());
  239. assertEquals("3.0", evaluator.evaluate(countA_1F).formatAsString());
  240. Cell countA_2F = s1.getRow(2).getCell(3);
  241. assertNotNull(countA_2F);
  242. assertEquals("COUNTA(Sheet1:Sheet3!D1)", countA_2F.getCellFormula());
  243. assertEquals("0.0", evaluator.evaluate(countA_2F).formatAsString());
  244. Cell countA_3F = s1.getRow(2).getCell(4);
  245. assertNotNull(countA_3F);
  246. assertEquals("COUNTA(Sheet1:Sheet3!E1)", countA_3F.getCellFormula());
  247. assertEquals("3.0", evaluator.evaluate(countA_3F).formatAsString());
  248. }
  249. }
  250. /**
  251. * A handful of functions (such as SUM, COUNTA, MIN) support
  252. * multi-sheet areas (eg Sheet1:Sheet3!A1:B2 = Cell A1 to Cell B2,
  253. * from Sheets 1 through Sheet 3).
  254. * This test, based on common test files for HSSF and XSSF, checks
  255. * that we can correctly evaluate these
  256. */
  257. @ParameterizedTest
  258. @ValueSource(strings = {"55906-MultiSheetRefs.xls","55906-MultiSheetRefs.xlsx"})
  259. public void testMultiSheetAreasHSSFandXSSF(String sampleFileName) throws Exception {
  260. Function<String, Workbook> fun = sampleFileName.endsWith("x")
  261. ? XSSFTestDataSamples::openSampleWorkbook : HSSFTestDataSamples::openSampleWorkbook;
  262. try (Workbook wb = fun.apply(sampleFileName)) {
  263. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  264. Sheet s1 = wb.getSheetAt(0);
  265. // SUM over a range
  266. Cell sumFA = s1.getRow(2).getCell(7);
  267. assertNotNull(sumFA);
  268. assertEquals("SUM(Sheet1:Sheet3!A1:B2)", sumFA.getCellFormula());
  269. assertEquals("110.0", evaluator.evaluate(sumFA).formatAsString(), "Failed for " + wb.getClass());
  270. // Various Stats formulas on ranges of numbers
  271. Cell avgFA = s1.getRow(2).getCell(8);
  272. assertNotNull(avgFA);
  273. assertEquals("AVERAGE(Sheet1:Sheet3!A1:B2)", avgFA.getCellFormula());
  274. assertEquals("27.5", evaluator.evaluate(avgFA).formatAsString());
  275. Cell minFA = s1.getRow(3).getCell(8);
  276. assertNotNull(minFA);
  277. assertEquals("MIN(Sheet1:Sheet3!A$1:B$2)", minFA.getCellFormula());
  278. assertEquals("11.0", evaluator.evaluate(minFA).formatAsString());
  279. Cell maxFA = s1.getRow(4).getCell(8);
  280. assertNotNull(maxFA);
  281. assertEquals("MAX(Sheet1:Sheet3!A$1:B$2)", maxFA.getCellFormula());
  282. assertEquals("44.0", evaluator.evaluate(maxFA).formatAsString());
  283. Cell countFA = s1.getRow(5).getCell(8);
  284. assertNotNull(countFA);
  285. assertEquals("COUNT(Sheet1:Sheet3!$A$1:$B$2)", countFA.getCellFormula());
  286. assertEquals("4.0", evaluator.evaluate(countFA).formatAsString());
  287. }
  288. }
  289. @ParameterizedTest
  290. @ValueSource(strings = {
  291. // bug 57721
  292. "evaluate_formula_with_structured_table_references.xlsx"
  293. // bug 57840:
  294. // Takes over a minute to evaluate all formulas in this large workbook. Run this test when profiling for formula evaluation speed.
  295. // , "StructuredRefs-lots-with-lookups.xlsx"
  296. })
  297. public void verifyAllFormulasInWorkbookCanBeEvaluated(String sampleWorkbook) throws IOException {
  298. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(sampleWorkbook)) {
  299. assertDoesNotThrow(() -> XSSFFormulaEvaluator.evaluateAllFormulaCells(wb));
  300. }
  301. }
  302. @Test
  303. public void test59736() throws IOException {
  304. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("59736.xlsx")) {
  305. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  306. Cell cell = wb.getSheetAt(0).getRow(0).getCell(0);
  307. assertEquals(1, cell.getNumericCellValue(), 0.001);
  308. cell = wb.getSheetAt(0).getRow(1).getCell(0);
  309. CellValue value = evaluator.evaluate(cell);
  310. assertEquals(1, value.getNumberValue(), 0.001);
  311. cell = wb.getSheetAt(0).getRow(2).getCell(0);
  312. value = evaluator.evaluate(cell);
  313. assertEquals(1, value.getNumberValue(), 0.001);
  314. }
  315. }
  316. @Test
  317. public void evaluateInCellReturnsSameDataType() throws IOException {
  318. try (XSSFWorkbook wb = new XSSFWorkbook()) {
  319. wb.createSheet().createRow(0).createCell(0);
  320. XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  321. XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0);
  322. XSSFCell same = evaluator.evaluateInCell(cell);
  323. assertSame(cell, same);
  324. }
  325. }
  326. @Test
  327. public void testBug61468() throws IOException {
  328. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("simple-monthly-budget.xlsx")) {
  329. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  330. Cell cell = wb.getSheetAt(0).getRow(8).getCell(4);
  331. assertEquals(3750, cell.getNumericCellValue(), 0.001);
  332. CellValue value = evaluator.evaluate(cell);
  333. assertEquals(3750, value.getNumberValue(), 0.001);
  334. }
  335. }
  336. @Test
  337. @Disabled("this is from an open bug/discussion over handling localization for number formats")
  338. public void testBug61495() throws IOException {
  339. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("61495-test.xlsm")) {
  340. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  341. Cell cell = wb.getSheetAt(0).getRow(0).getCell(1);
  342. // assertEquals("D 67.10", cell.getStringCellValue());
  343. String act = evaluator.evaluate(cell).getStringValue();
  344. assertEquals("D 67.10", act);
  345. cell = wb.getSheetAt(0).getRow(1).getCell(1);
  346. act = evaluator.evaluate(cell).getStringValue();
  347. assertEquals("D 0,068", act);
  348. }
  349. }
  350. /**
  351. * see bug 62834, handle when a shared formula range doesn't contain only formula cells
  352. */
  353. @Test
  354. public void testBug62834() throws IOException {
  355. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("62834.xlsx")) {
  356. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  357. Cell a2 = wb.getSheetAt(0).getRow(1).getCell(0);
  358. Cell value = evaluator.evaluateInCell(a2);
  359. assertEquals("a value", value.getStringCellValue(), "wrong value A2");
  360. // evaluator.clearAllCachedResultValues();
  361. Cell a3 = wb.getSheetAt(0).getRow(2).getCell(0);
  362. value = evaluator.evaluateInCell(a3);
  363. assertEquals("a value", value.getStringCellValue(), "wrong value A3");
  364. Cell a5 = wb.getSheetAt(0).getRow(4).getCell(0);
  365. value = evaluator.evaluateInCell(a5);
  366. assertEquals("another value", value.getStringCellValue(), "wrong value A5");
  367. }
  368. }
  369. }