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.

TestStructuredReferences.java 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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.ss.tests.formula;
  16. import static org.junit.jupiter.api.Assertions.assertEquals;
  17. import static org.junit.jupiter.api.Assertions.assertFalse;
  18. import static org.junit.jupiter.api.Assertions.assertTrue;
  19. import org.apache.poi.ss.SpreadsheetVersion;
  20. import org.apache.poi.ss.usermodel.Cell;
  21. import org.apache.poi.ss.usermodel.CellType;
  22. import org.apache.poi.ss.usermodel.CellValue;
  23. import org.apache.poi.ss.usermodel.FormulaEvaluator;
  24. import org.apache.poi.ss.usermodel.Row;
  25. import org.apache.poi.ss.usermodel.Table;
  26. import org.apache.poi.ss.util.AreaReference;
  27. import org.apache.poi.ss.util.CellReference;
  28. import org.apache.poi.xssf.XSSFTestDataSamples;
  29. import org.apache.poi.xssf.usermodel.*;
  30. import org.junit.jupiter.api.Test;
  31. /**
  32. * Tests Excel Table expressions (structured references)
  33. * @see <a href="https://support.office.com/en-us/article/Using-structured-references-with-Excel-tables-F5ED2452-2337-4F71-BED3-C8AE6D2B276E">
  34. * Excel Structured Reference Syntax
  35. * </a>
  36. */
  37. class TestStructuredReferences {
  38. /**
  39. * Test the regular expression used in INDIRECT() evaluation to recognize structured references
  40. */
  41. @Test
  42. void testTableExpressionSyntax() {
  43. assertTrue(Table.isStructuredReference.matcher("abc[col1]").matches(), "Valid structured reference syntax didn't match expression");
  44. assertTrue(Table.isStructuredReference.matcher("_abc[col1]").matches(), "Valid structured reference syntax didn't match expression");
  45. assertTrue(Table.isStructuredReference.matcher("_[col1]").matches(), "Valid structured reference syntax didn't match expression");
  46. assertTrue(Table.isStructuredReference.matcher("\\[col1]").matches(), "Valid structured reference syntax didn't match expression");
  47. assertTrue(Table.isStructuredReference.matcher("\\[col1]").matches(), "Valid structured reference syntax didn't match expression");
  48. assertTrue(Table.isStructuredReference.matcher("\\[#This Row]").matches(), "Valid structured reference syntax didn't match expression");
  49. assertTrue(Table.isStructuredReference.matcher("\\[ [col1], [col2] ]").matches(), "Valid structured reference syntax didn't match expression");
  50. // can't have a space between the table name and open bracket
  51. assertFalse(Table.isStructuredReference.matcher("\\abc [ [col1], [col2] ]").matches(), "Invalid structured reference syntax didn't fail expression");
  52. }
  53. @Test
  54. void testTableFormulas() throws Exception {
  55. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) {
  56. final FormulaEvaluator eval = new XSSFFormulaEvaluator(wb);
  57. final XSSFSheet tableSheet = wb.getSheet("Table");
  58. final XSSFSheet formulaSheet = wb.getSheet("Formulas");
  59. confirm(eval, tableSheet.getRow(5).getCell(0), 49);
  60. confirm(eval, formulaSheet.getRow(0).getCell(0), 209);
  61. confirm(eval, formulaSheet.getRow(1).getCell(0), "one");
  62. // test changing a table value, to see if the caches are properly cleared
  63. // Issue 59814
  64. // this test passes before the fix for 59814
  65. tableSheet.getRow(1).getCell(1).setCellValue("ONEA");
  66. confirm(eval, formulaSheet.getRow(1).getCell(0), "ONEA");
  67. // test adding a row to a table, issue 59814
  68. Row newRow = tableSheet.getRow(7);
  69. if (newRow == null) newRow = tableSheet.createRow(7);
  70. newRow.createCell(0, CellType.FORMULA).setCellFormula("\\_Prime.1[[#This Row],[@Number]]*\\_Prime.1[[#This Row],[@Number]]");
  71. newRow.createCell(1, CellType.STRING).setCellValue("thirteen");
  72. newRow.createCell(2, CellType.NUMERIC).setCellValue(13);
  73. // update Table
  74. final XSSFTable table = wb.getTable("\\_Prime.1");
  75. final AreaReference newArea = wb.getCreationHelper().createAreaReference(
  76. table.getStartCellReference(),
  77. new CellReference(table.getEndRowIndex() + 1, table.getEndColIndex()));
  78. String newAreaStr = newArea.formatAsString();
  79. table.getCTTable().setRef(newAreaStr);
  80. table.getCTTable().getAutoFilter().setRef(newAreaStr);
  81. table.updateHeaders();
  82. table.updateReferences();
  83. // these fail before the fix for 59814
  84. confirm(eval, tableSheet.getRow(7).getCell(0), 13 * 13);
  85. confirm(eval, formulaSheet.getRow(0).getCell(0), 209 + 13 * 13);
  86. }
  87. }
  88. @Test
  89. void testCellFormulaValidationFalse() throws Exception {
  90. //relates to https://bz.apache.org/bugzilla/show_bug.cgi?id=66039
  91. try (XSSFWorkbook workbook = new XSSFWorkbook()) {
  92. workbook.setCellFormulaValidation(false);
  93. XSSFSheet sheet = workbook.createSheet();
  94. //set sheet content
  95. sheet.createRow(0).createCell(0).setCellValue("Field1");
  96. sheet.getRow(0).createCell(1).setCellValue("Field2");
  97. sheet.createRow(1).createCell(0).setCellValue(123);
  98. sheet.getRow(1).createCell(1);
  99. //create the table
  100. String tableName = "Table1";
  101. CellReference topLeft = new CellReference(sheet.getRow(0).getCell(0));
  102. CellReference bottomRight = new CellReference(sheet.getRow(1).getCell(1));
  103. AreaReference tableArea = workbook.getCreationHelper().createAreaReference(topLeft, bottomRight);
  104. XSSFTable dataTable = sheet.createTable(tableArea);
  105. dataTable.setName(tableName);
  106. dataTable.setDisplayName(tableName);
  107. //set the formula in sheet - when setCellFormulaValidation=true (the default), the code tries to
  108. //tidy up this formula (but incorrectly, in this case) - gets adjusted to Sheet0!A2:A2
  109. XSSFCell formulaCell = sheet.getRow(1).getCell(1);
  110. formulaCell.setCellFormula(tableName + "[[#This Row],[Field1]]");
  111. assertEquals("Table1[[#This Row],[Field1]]", formulaCell.getCellFormula());
  112. }
  113. }
  114. @Test
  115. void testBug66215() throws Exception {
  116. //relates to https://bz.apache.org/bugzilla/show_bug.cgi?id=66215 (this does not work as it should)
  117. try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("bug66215.xlsx")) {
  118. XSSFSheet sheet = workbook.getSheetAt(0);
  119. XSSFRow row3 = sheet.getRow(3);
  120. XSSFRow row5 = sheet.getRow(5);
  121. assertEquals("Tabelle1[[#This Row],[Total]]/Tabelle1[[#Totals],[Total]]", row3.getCell(5).getCellFormula());
  122. assertEquals("Tabelle1[[#This Row],[Total]]/Tabelle1[[#Totals],[Total]]", row5.getCell(5).getCellFormula());
  123. XSSFTable table = sheet.getTables().get(0);
  124. int lastTableRow = table.getEndCellReference().getRow();
  125. int totalsRowCount = table.getTotalsRowCount();
  126. int lastTableDataRow = lastTableRow - totalsRowCount;
  127. // we will add one row in table data
  128. lastTableRow++;
  129. lastTableDataRow++;
  130. // new table area plus one row
  131. AreaReference newTableArea = new AreaReference(
  132. table.getStartCellReference(),
  133. new CellReference(
  134. lastTableRow,
  135. table.getEndCellReference().getCol()
  136. ),
  137. SpreadsheetVersion.EXCEL2007
  138. );
  139. if (totalsRowCount > 0) {
  140. workbook.setCellFormulaValidation(false);
  141. sheet.shiftRows(lastTableDataRow, lastTableRow++, 1);
  142. }
  143. // set new table area
  144. table.setArea(newTableArea);
  145. XSSFRow row4 = sheet.getRow(4);
  146. //the next formula has been adjusted more than it should but seems to return correct value
  147. assertEquals("Tabelle2!E5:E5/Tabelle2!E8:E8", row4.getCell(5).getCellFormula());
  148. XSSFRow row7 = sheet.getRow(7);
  149. //the next formula is completely wrong (should be the same as the value in the row4 assertion above)
  150. assertEquals("SUBTOTAL(109,Tabelle1[Percentage])", row7.getCell(5).getCellFormula());
  151. }
  152. }
  153. private static void confirm(FormulaEvaluator fe, Cell cell, double expectedResult) {
  154. fe.clearAllCachedResultValues();
  155. CellValue cv = fe.evaluate(cell);
  156. assertEquals(CellType.NUMERIC, cv.getCellType(), "expected numeric cell type but got " + cv.formatAsString());
  157. assertEquals(expectedResult, cv.getNumberValue(), 0.0);
  158. }
  159. private static void confirm(FormulaEvaluator fe, Cell cell, String expectedResult) {
  160. fe.clearAllCachedResultValues();
  161. CellValue cv = fe.evaluate(cell);
  162. assertEquals(CellType.STRING, cv.getCellType(), "expected String cell type but got " + cv.formatAsString());
  163. assertEquals(expectedResult, cv.getStringValue());
  164. }
  165. }