Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

TestXSSFFormulaEvaluation.java 19KB

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