Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

TestXSSFFormulaEvaluation.java 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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.Assert.assertEquals;
  17. import static org.junit.Assert.assertNotNull;
  18. import static org.junit.Assert.assertSame;
  19. import static org.junit.Assert.fail;
  20. import java.io.IOException;
  21. import java.util.HashMap;
  22. import java.util.Map;
  23. import org.apache.poi.hssf.HSSFTestDataSamples;
  24. import org.apache.poi.ss.usermodel.BaseTestFormulaEvaluator;
  25. import org.apache.poi.ss.usermodel.Cell;
  26. import org.apache.poi.ss.usermodel.CellValue;
  27. import org.apache.poi.ss.usermodel.FormulaEvaluator;
  28. import org.apache.poi.ss.usermodel.Row;
  29. import org.apache.poi.ss.usermodel.Sheet;
  30. import org.apache.poi.ss.usermodel.Workbook;
  31. import org.apache.poi.ss.util.CellReference;
  32. import org.apache.poi.xssf.XSSFITestDataProvider;
  33. import org.apache.poi.xssf.XSSFTestDataSamples;
  34. import org.junit.Ignore;
  35. import org.junit.Test;
  36. public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
  37. public TestXSSFFormulaEvaluation() {
  38. super(XSSFITestDataProvider.instance);
  39. }
  40. @Test
  41. public void testSharedFormulas() throws IOException {
  42. baseTestSharedFormulas("shared_formulas.xlsx");
  43. }
  44. @Test
  45. public void testSharedFormulas_evaluateInCell() throws IOException {
  46. try (XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("49872.xlsx")) {
  47. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  48. XSSFSheet 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. XSSFCell 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. XSSFCell c3 = sheet.getRow(2).getCell(2);
  60. assertEquals(result, evaluator.evaluateInCell(c3).getNumericCellValue(), 0);
  61. XSSFCell 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 (XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("50096.xlsx")) {
  71. XSSFFormulaEvaluator 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. XSSFCell cell_noformula = wb.getSheetAt(0).getRow(0).getCell(i);
  78. XSSFCell 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("Wrong evaluation result in " + ref_formula.formatAsString(),
  89. cv_noformula.getNumberValue(), cv_formula.getNumberValue(), 0);
  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 (XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("ref2-56737.xlsx")) {
  101. XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  102. XSSFSheet 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. try {
  128. evaluator.evaluate(cXSL_cell);
  129. fail("Without a fix for #56752, shouldn't be able to evaluate a " +
  130. "reference to a non-provided linked workbook");
  131. } catch (Exception e) {
  132. // expected here
  133. }
  134. // Setup the environment
  135. Map<String, FormulaEvaluator> evaluators = new HashMap<>();
  136. evaluators.put("ref2-56737.xlsx", evaluator);
  137. Workbook wbEval1 = _testDataProvider.openSampleWorkbook("56737.xlsx");
  138. evaluators.put("56737.xlsx",
  139. wbEval1.getCreationHelper().createFormulaEvaluator());
  140. Workbook wbEval2 = HSSFTestDataSamples.openSampleWorkbook("56737.xls");
  141. evaluators.put("56737.xls",
  142. wbEval2.getCreationHelper().createFormulaEvaluator());
  143. evaluator.setupReferencedWorkbooks(evaluators);
  144. // Try evaluating all of them, ensure we don't blow up
  145. for (Row r : s) {
  146. for (Cell c : r) {
  147. evaluator.evaluate(c);
  148. }
  149. }
  150. // And evaluate the other way too
  151. evaluator.evaluateAll();
  152. // Static evaluator won't work, as no references passed in
  153. try {
  154. XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
  155. fail("Static method lacks references, shouldn't work");
  156. } catch (Exception e) {
  157. // expected here
  158. }
  159. // Evaluate specific cells and check results
  160. assertEquals("\"Hello!\"", evaluator.evaluate(cXSLX_cell).formatAsString());
  161. assertEquals("\"Test A1\"", evaluator.evaluate(cXSLX_sNR).formatAsString());
  162. assertEquals("142.0", evaluator.evaluate(cXSLX_gNR).formatAsString());
  163. assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell).formatAsString());
  164. assertEquals("\"Test A1\"", evaluator.evaluate(cXSL_sNR).formatAsString());
  165. assertEquals("142.0", evaluator.evaluate(cXSL_gNR).formatAsString());
  166. // Add another formula referencing these workbooks
  167. Cell cXSL_cell2 = rXSL.createCell(40);
  168. cXSL_cell2.setCellFormula("[56737.xls]Uses!$C$1");
  169. // TODO Shouldn't it become [2] like the others?
  170. assertEquals("[56737.xls]Uses!$C$1", cXSL_cell2.getCellFormula());
  171. assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell2).formatAsString());
  172. // Now add a formula that refers to yet another (different) workbook
  173. // Won't work without the workbook being linked
  174. Cell cXSLX_nw_cell = rXSLX.createCell(42);
  175. try {
  176. cXSLX_nw_cell.setCellFormula("[alt.xlsx]Sheet1!$A$1");
  177. fail("New workbook not linked, shouldn't be able to add");
  178. } catch (Exception e) {
  179. // expected here
  180. }
  181. wbEval1.close();
  182. wbEval2.close();
  183. // Link and re-try
  184. try (Workbook alt = new XSSFWorkbook()) {
  185. alt.createSheet().createRow(0).createCell(0).setCellValue("In another workbook");
  186. // TODO Implement the rest of this, see bug #57184
  187. /*
  188. wb.linkExternalWorkbook("alt.xlsx", alt);
  189. cXSLX_nw_cell.setCellFormula("[alt.xlsx]Sheet1!$A$1");
  190. // Check it - TODO Is this correct? Or should it become [3]Sheet1!$A$1 ?
  191. assertEquals("[alt.xlsx]Sheet1!$A$1", cXSLX_nw_cell.getCellFormula());
  192. // Evaluate it, without a link to that workbook
  193. try {
  194. evaluator.evaluate(cXSLX_nw_cell);
  195. fail("No cached value and no link to workbook, shouldn't evaluate");
  196. } catch(Exception e) {}
  197. // Add a link, check it does
  198. evaluators.put("alt.xlsx", alt.getCreationHelper().createFormulaEvaluator());
  199. evaluator.setupReferencedWorkbooks(evaluators);
  200. evaluator.evaluate(cXSLX_nw_cell);
  201. assertEquals("In another workbook", cXSLX_nw_cell.getStringCellValue());
  202. */
  203. }
  204. }
  205. }
  206. /**
  207. * If a formula references cells or named ranges in another workbook,
  208. * but that isn't available at evaluation time, the cached values
  209. * should be used instead
  210. * TODO Add the support then add a unit test
  211. * See bug #56752
  212. */
  213. @Test
  214. @Ignore
  215. public void testCachedReferencesToOtherWorkbooks() {
  216. // TODO
  217. fail("unit test not written yet");
  218. }
  219. /**
  220. * A handful of functions (such as SUM, COUNTA, MIN) support
  221. * multi-sheet references (eg Sheet1:Sheet3!A1 = Cell A1 from
  222. * Sheets 1 through Sheet 3).
  223. * This test, based on common test files for HSSF and XSSF, checks
  224. * that we can correctly evaluate these
  225. */
  226. @Test
  227. public void testMultiSheetReferencesHSSFandXSSF() throws Exception {
  228. Workbook wb1 = HSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xls");
  229. Workbook wb2 = XSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xlsx");
  230. for (Workbook wb : new Workbook[] {wb1,wb2}) {
  231. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  232. Sheet s1 = wb.getSheetAt(0);
  233. // Simple SUM over numbers
  234. Cell sumF = s1.getRow(2).getCell(0);
  235. assertNotNull(sumF);
  236. assertEquals("SUM(Sheet1:Sheet3!A1)", sumF.getCellFormula());
  237. assertEquals("Failed for " + wb.getClass(), "66.0", evaluator.evaluate(sumF).formatAsString());
  238. // Various Stats formulas on numbers
  239. Cell avgF = s1.getRow(2).getCell(1);
  240. assertNotNull(avgF);
  241. assertEquals("AVERAGE(Sheet1:Sheet3!A1)", avgF.getCellFormula());
  242. assertEquals("22.0", evaluator.evaluate(avgF).formatAsString());
  243. Cell minF = s1.getRow(3).getCell(1);
  244. assertNotNull(minF);
  245. assertEquals("MIN(Sheet1:Sheet3!A$1)", minF.getCellFormula());
  246. assertEquals("11.0", evaluator.evaluate(minF).formatAsString());
  247. Cell maxF = s1.getRow(4).getCell(1);
  248. assertNotNull(maxF);
  249. assertEquals("MAX(Sheet1:Sheet3!A$1)", maxF.getCellFormula());
  250. assertEquals("33.0", evaluator.evaluate(maxF).formatAsString());
  251. Cell countF = s1.getRow(5).getCell(1);
  252. assertNotNull(countF);
  253. assertEquals("COUNT(Sheet1:Sheet3!A$1)", countF.getCellFormula());
  254. assertEquals("3.0", evaluator.evaluate(countF).formatAsString());
  255. // Various CountAs on Strings
  256. Cell countA_1F = s1.getRow(2).getCell(2);
  257. assertNotNull(countA_1F);
  258. assertEquals("COUNTA(Sheet1:Sheet3!C1)", countA_1F.getCellFormula());
  259. assertEquals("3.0", evaluator.evaluate(countA_1F).formatAsString());
  260. Cell countA_2F = s1.getRow(2).getCell(3);
  261. assertNotNull(countA_2F);
  262. assertEquals("COUNTA(Sheet1:Sheet3!D1)", countA_2F.getCellFormula());
  263. assertEquals("0.0", evaluator.evaluate(countA_2F).formatAsString());
  264. Cell countA_3F = s1.getRow(2).getCell(4);
  265. assertNotNull(countA_3F);
  266. assertEquals("COUNTA(Sheet1:Sheet3!E1)", countA_3F.getCellFormula());
  267. assertEquals("3.0", evaluator.evaluate(countA_3F).formatAsString());
  268. }
  269. wb2.close();
  270. wb1.close();
  271. }
  272. /**
  273. * A handful of functions (such as SUM, COUNTA, MIN) support
  274. * multi-sheet areas (eg Sheet1:Sheet3!A1:B2 = Cell A1 to Cell B2,
  275. * from Sheets 1 through Sheet 3).
  276. * This test, based on common test files for HSSF and XSSF, checks
  277. * that we can correctly evaluate these
  278. */
  279. @Test
  280. public void testMultiSheetAreasHSSFandXSSF() throws IOException {
  281. Workbook wb1 = HSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xls");
  282. Workbook wb2 = XSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xlsx");
  283. for (Workbook wb : new Workbook[]{wb1,wb2}) {
  284. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  285. Sheet s1 = wb.getSheetAt(0);
  286. // SUM over a range
  287. Cell sumFA = s1.getRow(2).getCell(7);
  288. assertNotNull(sumFA);
  289. assertEquals("SUM(Sheet1:Sheet3!A1:B2)", sumFA.getCellFormula());
  290. assertEquals("Failed for " + wb.getClass(), "110.0", evaluator.evaluate(sumFA).formatAsString());
  291. // Various Stats formulas on ranges of numbers
  292. Cell avgFA = s1.getRow(2).getCell(8);
  293. assertNotNull(avgFA);
  294. assertEquals("AVERAGE(Sheet1:Sheet3!A1:B2)", avgFA.getCellFormula());
  295. assertEquals("27.5", evaluator.evaluate(avgFA).formatAsString());
  296. Cell minFA = s1.getRow(3).getCell(8);
  297. assertNotNull(minFA);
  298. assertEquals("MIN(Sheet1:Sheet3!A$1:B$2)", minFA.getCellFormula());
  299. assertEquals("11.0", evaluator.evaluate(minFA).formatAsString());
  300. Cell maxFA = s1.getRow(4).getCell(8);
  301. assertNotNull(maxFA);
  302. assertEquals("MAX(Sheet1:Sheet3!A$1:B$2)", maxFA.getCellFormula());
  303. assertEquals("44.0", evaluator.evaluate(maxFA).formatAsString());
  304. Cell countFA = s1.getRow(5).getCell(8);
  305. assertNotNull(countFA);
  306. assertEquals("COUNT(Sheet1:Sheet3!$A$1:$B$2)", countFA.getCellFormula());
  307. assertEquals("4.0", evaluator.evaluate(countFA).formatAsString());
  308. }
  309. wb2.close();
  310. wb1.close();
  311. }
  312. // bug 57721
  313. @Test
  314. public void structuredReferences() throws IOException {
  315. verifyAllFormulasInWorkbookCanBeEvaluated("evaluate_formula_with_structured_table_references.xlsx");
  316. }
  317. // bug 57840
  318. @Ignore("Takes over a minute to evaluate all formulas in this large workbook. Run this test when profiling for formula evaluation speed.")
  319. @Test
  320. public void testLotsOfFormulasWithStructuredReferencesToCalculatedTableColumns() throws IOException {
  321. verifyAllFormulasInWorkbookCanBeEvaluated("StructuredRefs-lots-with-lookups.xlsx");
  322. }
  323. // FIXME: use junit4 parametrization
  324. private static void verifyAllFormulasInWorkbookCanBeEvaluated(String sampleWorkbook) throws IOException {
  325. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(sampleWorkbook)) {
  326. XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
  327. }
  328. }
  329. @Test
  330. public void test59736() throws IOException {
  331. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("59736.xlsx")) {
  332. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  333. Cell cell = wb.getSheetAt(0).getRow(0).getCell(0);
  334. assertEquals(1, cell.getNumericCellValue(), 0.001);
  335. cell = wb.getSheetAt(0).getRow(1).getCell(0);
  336. CellValue value = evaluator.evaluate(cell);
  337. assertEquals(1, value.getNumberValue(), 0.001);
  338. cell = wb.getSheetAt(0).getRow(2).getCell(0);
  339. value = evaluator.evaluate(cell);
  340. assertEquals(1, value.getNumberValue(), 0.001);
  341. }
  342. }
  343. @Test
  344. public void evaluateInCellReturnsSameDataType() throws IOException {
  345. try (XSSFWorkbook wb = new XSSFWorkbook()) {
  346. wb.createSheet().createRow(0).createCell(0);
  347. XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  348. XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0);
  349. XSSFCell same = evaluator.evaluateInCell(cell);
  350. assertSame(cell, same);
  351. }
  352. }
  353. @Test
  354. public void testBug61468() throws IOException {
  355. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("simple-monthly-budget.xlsx")) {
  356. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  357. Cell cell = wb.getSheetAt(0).getRow(8).getCell(4);
  358. assertEquals(3750, cell.getNumericCellValue(), 0.001);
  359. CellValue value = evaluator.evaluate(cell);
  360. assertEquals(3750, value.getNumberValue(), 0.001);
  361. }
  362. }
  363. @Test
  364. @Ignore // this is from an open bug/discussion over handling localization for number formats
  365. public void testBug61495() throws IOException {
  366. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("61495-test.xlsm")) {
  367. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  368. Cell cell = wb.getSheetAt(0).getRow(0).getCell(1);
  369. // assertEquals("D 67.10", cell.getStringCellValue());
  370. CellValue value = evaluator.evaluate(cell);
  371. assertEquals("D 67.10",
  372. value.getStringValue());
  373. assertEquals("D 0,068",
  374. evaluator.evaluate(wb.getSheetAt(0).getRow(1).getCell(1)).getStringValue());
  375. }
  376. }
  377. /**
  378. * see bug 62834, handle when a shared formula range doesn't contain only formula cells
  379. */
  380. @Test
  381. public void testBug62834() throws IOException {
  382. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("62834.xlsx")) {
  383. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  384. Cell a2 = wb.getSheetAt(0).getRow(1).getCell(0);
  385. Cell value = evaluator.evaluateInCell(a2);
  386. assertEquals("wrong value A2", "a value", value.getStringCellValue());
  387. // evaluator.clearAllCachedResultValues();
  388. Cell a3 = wb.getSheetAt(0).getRow(2).getCell(0);
  389. value = evaluator.evaluateInCell(a3);
  390. assertEquals("wrong value A3", "a value", value.getStringCellValue());
  391. Cell a5 = wb.getSheetAt(0).getRow(4).getCell(0);
  392. value = evaluator.evaluateInCell(a5);
  393. assertEquals("wrong value A5", "another value", value.getStringCellValue());
  394. }
  395. }
  396. }