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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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 java.util.HashMap;
  17. import java.util.Map;
  18. import org.apache.poi.hssf.HSSFTestDataSamples;
  19. import org.apache.poi.ss.usermodel.BaseTestFormulaEvaluator;
  20. import org.apache.poi.ss.usermodel.Cell;
  21. import org.apache.poi.ss.usermodel.CellValue;
  22. import org.apache.poi.ss.usermodel.FormulaEvaluator;
  23. import org.apache.poi.ss.usermodel.Row;
  24. import org.apache.poi.ss.usermodel.Sheet;
  25. import org.apache.poi.ss.usermodel.Workbook;
  26. import org.apache.poi.ss.util.CellReference;
  27. import org.apache.poi.xssf.XSSFITestDataProvider;
  28. import org.apache.poi.xssf.XSSFTestDataSamples;
  29. public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
  30. public TestXSSFFormulaEvaluation() {
  31. super(XSSFITestDataProvider.instance);
  32. }
  33. public void testSharedFormulas(){
  34. baseTestSharedFormulas("shared_formulas.xlsx");
  35. }
  36. public void testSharedFormulas_evaluateInCell(){
  37. XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("49872.xlsx");
  38. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  39. XSSFSheet sheet = wb.getSheetAt(0);
  40. double result = 3.0;
  41. // B3 is a master shared formula, C3 and D3 don't have the formula written in their f element.
  42. // Instead, the attribute si for a particular cell is used to figure what the formula expression
  43. // should be based on the cell's relative location to the master formula, e.g.
  44. // B3: <f t="shared" ref="B3:D3" si="0">B1+B2</f>
  45. // C3 and D3: <f t="shared" si="0"/>
  46. // get B3 and evaluate it in the cell
  47. XSSFCell b3 = sheet.getRow(2).getCell(1);
  48. assertEquals(result, evaluator.evaluateInCell(b3).getNumericCellValue());
  49. //at this point the master formula is gone, but we are still able to evaluate dependent cells
  50. XSSFCell c3 = sheet.getRow(2).getCell(2);
  51. assertEquals(result, evaluator.evaluateInCell(c3).getNumericCellValue());
  52. XSSFCell d3 = sheet.getRow(2).getCell(3);
  53. assertEquals(result, evaluator.evaluateInCell(d3).getNumericCellValue());
  54. }
  55. /**
  56. * Evaluation of cell references with column indexes greater than 255. See bugzilla 50096
  57. */
  58. public void testEvaluateColumnGreaterThan255() {
  59. XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("50096.xlsx");
  60. XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  61. /**
  62. * The first row simply contains the numbers 1 - 300.
  63. * The second row simply refers to the cell value above in the first row by a simple formula.
  64. */
  65. for (int i = 245; i < 265; i++) {
  66. XSSFCell cell_noformula = wb.getSheetAt(0).getRow(0).getCell(i);
  67. XSSFCell cell_formula = wb.getSheetAt(0).getRow(1).getCell(i);
  68. CellReference ref_noformula = new CellReference(cell_noformula.getRowIndex(), cell_noformula.getColumnIndex());
  69. CellReference ref_formula = new CellReference(cell_noformula.getRowIndex(), cell_noformula.getColumnIndex());
  70. String fmla = cell_formula.getCellFormula();
  71. // assure that the formula refers to the cell above.
  72. // the check below is 'deep' and involves conversion of the shared formula:
  73. // in the sample file a shared formula in GN1 is spanned in the range GN2:IY2,
  74. assertEquals(ref_noformula.formatAsString(), fmla);
  75. CellValue cv_noformula = evaluator.evaluate(cell_noformula);
  76. CellValue cv_formula = evaluator.evaluate(cell_formula);
  77. assertEquals("Wrong evaluation result in " + ref_formula.formatAsString(),
  78. cv_noformula.getNumberValue(), cv_formula.getNumberValue());
  79. }
  80. }
  81. /**
  82. * Related to bugs #56737 and #56752 - XSSF workbooks which have
  83. * formulas that refer to cells and named ranges in multiple other
  84. * workbooks, both HSSF and XSSF ones
  85. */
  86. public void testReferencesToOtherWorkbooks() throws Exception {
  87. XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("ref2-56737.xlsx");
  88. XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  89. XSSFSheet s = wb.getSheetAt(0);
  90. // References to a .xlsx file
  91. Row rXSLX = s.getRow(2);
  92. Cell cXSLX_cell = rXSLX.getCell(4);
  93. Cell cXSLX_sNR = rXSLX.getCell(6);
  94. Cell cXSLX_gNR = rXSLX.getCell(8);
  95. assertEquals("[1]Uses!$A$1", cXSLX_cell.getCellFormula());
  96. assertEquals("[1]Defines!NR_To_A1", cXSLX_sNR.getCellFormula());
  97. assertEquals("[1]!NR_Global_B2", cXSLX_gNR.getCellFormula());
  98. assertEquals("Hello!", cXSLX_cell.getStringCellValue());
  99. assertEquals("Test A1", cXSLX_sNR.getStringCellValue());
  100. assertEquals(142.0, cXSLX_gNR.getNumericCellValue());
  101. // References to a .xls file
  102. Row rXSL = s.getRow(4);
  103. Cell cXSL_cell = rXSL.getCell(4);
  104. Cell cXSL_sNR = rXSL.getCell(6);
  105. Cell cXSL_gNR = rXSL.getCell(8);
  106. assertEquals("[2]Uses!$C$1", cXSL_cell.getCellFormula());
  107. assertEquals("[2]Defines!NR_To_A1", cXSL_sNR.getCellFormula());
  108. assertEquals("[2]!NR_Global_B2", cXSL_gNR.getCellFormula());
  109. assertEquals("Hello!", cXSL_cell.getStringCellValue());
  110. assertEquals("Test A1", cXSL_sNR.getStringCellValue());
  111. assertEquals(142.0, cXSL_gNR.getNumericCellValue());
  112. // Try to evaluate without references, won't work
  113. // (At least, not unit we fix bug #56752 that is)
  114. try {
  115. evaluator.evaluate(cXSL_cell);
  116. fail("Without a fix for #56752, shouldn't be able to evaluate a " +
  117. "reference to a non-provided linked workbook");
  118. } catch(Exception e) {}
  119. // Setup the environment
  120. Map<String,FormulaEvaluator> evaluators = new HashMap<String, FormulaEvaluator>();
  121. evaluators.put("ref2-56737.xlsx", evaluator);
  122. evaluators.put("56737.xlsx",
  123. _testDataProvider.openSampleWorkbook("56737.xlsx").getCreationHelper().createFormulaEvaluator());
  124. evaluators.put("56737.xls",
  125. HSSFTestDataSamples.openSampleWorkbook("56737.xls").getCreationHelper().createFormulaEvaluator());
  126. evaluator.setupReferencedWorkbooks(evaluators);
  127. // Try evaluating all of them, ensure we don't blow up
  128. for(Row r : s) {
  129. for (Cell c : r) {
  130. evaluator.evaluate(c);
  131. }
  132. }
  133. // Evaluate and check results
  134. assertEquals("\"Hello!\"", evaluator.evaluate(cXSLX_cell).formatAsString());
  135. assertEquals("\"Test A1\"", evaluator.evaluate(cXSLX_sNR).formatAsString());
  136. assertEquals("142.0", evaluator.evaluate(cXSLX_gNR).formatAsString());
  137. assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell).formatAsString());
  138. assertEquals("\"Test A1\"", evaluator.evaluate(cXSL_sNR).formatAsString());
  139. assertEquals("142.0", evaluator.evaluate(cXSL_gNR).formatAsString());
  140. }
  141. /**
  142. * If a formula references cells or named ranges in another workbook,
  143. * but that isn't available at evaluation time, the cached values
  144. * should be used instead
  145. * TODO Add the support then add a unit test
  146. * See bug #56752
  147. */
  148. public void TODOtestCachedReferencesToOtherWorkbooks() throws Exception {
  149. // TODO
  150. }
  151. /**
  152. * A handful of functions (such as SUM, COUNTA, MIN) support
  153. * multi-sheet references (eg Sheet1:Sheet3!A1 = Cell A1 from
  154. * Sheets 1 through Sheet 3).
  155. * This test, based on common test files for HSSF and XSSF, checks
  156. * that we can correctly evaluate these
  157. */
  158. public void testMultiSheetReferencesHSSFandXSSF() throws Exception {
  159. Workbook[] wbs = new Workbook[] {
  160. HSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xls"),
  161. XSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xlsx")
  162. };
  163. for (Workbook wb : wbs) {
  164. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  165. Sheet s1 = wb.getSheetAt(0);
  166. // Simple SUM over numbers
  167. Cell sumF = s1.getRow(2).getCell(0);
  168. assertNotNull(sumF);
  169. assertEquals("SUM(Sheet1:Sheet3!A1)", sumF.getCellFormula());
  170. assertEquals("Failed for " + wb.getClass(), "66.0", evaluator.evaluate(sumF).formatAsString());
  171. // Various Stats formulas on numbers
  172. Cell avgF = s1.getRow(2).getCell(1);
  173. assertNotNull(avgF);
  174. assertEquals("AVERAGE(Sheet1:Sheet3!A1)", avgF.getCellFormula());
  175. assertEquals("22.0", evaluator.evaluate(avgF).formatAsString());
  176. Cell minF = s1.getRow(3).getCell(1);
  177. assertNotNull(minF);
  178. assertEquals("MIN(Sheet1:Sheet3!A$1)", minF.getCellFormula());
  179. assertEquals("11.0", evaluator.evaluate(minF).formatAsString());
  180. Cell maxF = s1.getRow(4).getCell(1);
  181. assertNotNull(maxF);
  182. assertEquals("MAX(Sheet1:Sheet3!A$1)", maxF.getCellFormula());
  183. assertEquals("33.0", evaluator.evaluate(maxF).formatAsString());
  184. Cell countF = s1.getRow(5).getCell(1);
  185. assertNotNull(countF);
  186. assertEquals("COUNT(Sheet1:Sheet3!A$1)", countF.getCellFormula());
  187. assertEquals("3.0", evaluator.evaluate(countF).formatAsString());
  188. // Various CountAs on Strings
  189. Cell countA_1F = s1.getRow(2).getCell(2);
  190. assertNotNull(countA_1F);
  191. assertEquals("COUNTA(Sheet1:Sheet3!C1)", countA_1F.getCellFormula());
  192. assertEquals("3.0", evaluator.evaluate(countA_1F).formatAsString());
  193. Cell countA_2F = s1.getRow(2).getCell(3);
  194. assertNotNull(countA_2F);
  195. assertEquals("COUNTA(Sheet1:Sheet3!D1)", countA_2F.getCellFormula());
  196. assertEquals("0.0", evaluator.evaluate(countA_2F).formatAsString());
  197. Cell countA_3F = s1.getRow(2).getCell(4);
  198. assertNotNull(countA_3F);
  199. assertEquals("COUNTA(Sheet1:Sheet3!E1)", countA_3F.getCellFormula());
  200. assertEquals("3.0", evaluator.evaluate(countA_3F).formatAsString());
  201. }
  202. }
  203. /**
  204. * A handful of functions (such as SUM, COUNTA, MIN) support
  205. * multi-sheet areas (eg Sheet1:Sheet3!A1:B2 = Cell A1 to Cell B2,
  206. * from Sheets 1 through Sheet 3).
  207. * This test, based on common test files for HSSF and XSSF, checks
  208. * that we can correctly evaluate these
  209. */
  210. public void testMultiSheetAreasHSSFandXSSF() throws Exception {
  211. Workbook[] wbs = new Workbook[] {
  212. HSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xls"),
  213. XSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xlsx")
  214. };
  215. for (Workbook wb : wbs) {
  216. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  217. Sheet s1 = wb.getSheetAt(0);
  218. // SUM over a range
  219. Cell sumFA = s1.getRow(2).getCell(7);
  220. assertNotNull(sumFA);
  221. assertEquals("SUM(Sheet1:Sheet3!A1:B2)", sumFA.getCellFormula());
  222. assertEquals("Failed for " + wb.getClass(), "110.0", evaluator.evaluate(sumFA).formatAsString());
  223. // Various Stats formulas on ranges of numbers
  224. Cell avgFA = s1.getRow(2).getCell(8);
  225. assertNotNull(avgFA);
  226. assertEquals("AVERAGE(Sheet1:Sheet3!A1:B2)", avgFA.getCellFormula());
  227. assertEquals("27.5", evaluator.evaluate(avgFA).formatAsString());
  228. Cell minFA = s1.getRow(3).getCell(8);
  229. assertNotNull(minFA);
  230. assertEquals("MIN(Sheet1:Sheet3!A$1:B$2)", minFA.getCellFormula());
  231. assertEquals("11.0", evaluator.evaluate(minFA).formatAsString());
  232. Cell maxFA = s1.getRow(4).getCell(8);
  233. assertNotNull(maxFA);
  234. assertEquals("MAX(Sheet1:Sheet3!A$1:B$2)", maxFA.getCellFormula());
  235. assertEquals("44.0", evaluator.evaluate(maxFA).formatAsString());
  236. Cell countFA = s1.getRow(5).getCell(8);
  237. assertNotNull(countFA);
  238. assertEquals("COUNT(Sheet1:Sheet3!$A$1:$B$2)", countFA.getCellFormula());
  239. assertEquals("4.0", evaluator.evaluate(countFA).formatAsString());
  240. }
  241. }
  242. public void testMultisheetFormulaEval() {
  243. XSSFWorkbook wb = new XSSFWorkbook();
  244. XSSFSheet sheet1 = wb.createSheet("Sheet1");
  245. XSSFSheet sheet2 = wb.createSheet("Sheet2");
  246. XSSFSheet sheet3 = wb.createSheet("Sheet3");
  247. // sheet1 A1
  248. XSSFCell cell = sheet1.createRow(0).createCell(0);
  249. cell.setCellType(Cell.CELL_TYPE_NUMERIC);
  250. cell.setCellValue(1.0);
  251. // sheet2 A1
  252. cell = sheet2.createRow(0).createCell(0);
  253. cell.setCellType(Cell.CELL_TYPE_NUMERIC);
  254. cell.setCellValue(1.0);
  255. // sheet2 B1
  256. cell = sheet2.getRow(0).createCell(1);
  257. cell.setCellType(Cell.CELL_TYPE_NUMERIC);
  258. cell.setCellValue(1.0);
  259. // sheet3 A1
  260. cell = sheet3.createRow(0).createCell(0);
  261. cell.setCellType(Cell.CELL_TYPE_NUMERIC);
  262. cell.setCellValue(1.0);
  263. // sheet1 A2 formulae
  264. cell = sheet1.createRow(1).createCell(0);
  265. cell.setCellType(Cell.CELL_TYPE_FORMULA);
  266. cell.setCellFormula("SUM(Sheet1:Sheet3!A1)");
  267. // sheet1 A3 formulae
  268. cell = sheet1.createRow(2).createCell(0);
  269. cell.setCellType(Cell.CELL_TYPE_FORMULA);
  270. cell.setCellFormula("SUM(Sheet1:Sheet3!A1:B1)");
  271. wb.getCreationHelper().createFormulaEvaluator().evaluateAll();
  272. cell = sheet1.getRow(1).getCell(0);
  273. assertEquals(3.0, cell.getNumericCellValue());
  274. cell = sheet1.getRow(2).getCell(0);
  275. assertEquals(4.0, cell.getNumericCellValue());
  276. }
  277. }