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.

TestSharedFormulaRecord.java 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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.hssf.record;
  16. import junit.framework.AssertionFailedError;
  17. import junit.framework.ComparisonFailure;
  18. import junit.framework.TestCase;
  19. import org.apache.poi.hssf.HSSFTestDataSamples;
  20. import org.apache.poi.hssf.record.formula.Ptg;
  21. import org.apache.poi.hssf.record.formula.RefPtg;
  22. import org.apache.poi.hssf.record.formula.SharedFormula;
  23. import org.apache.poi.hssf.usermodel.*;
  24. import org.apache.poi.ss.usermodel.CellValue;
  25. import org.apache.poi.ss.formula.FormulaParser;
  26. import org.apache.poi.ss.formula.FormulaRenderer;
  27. import org.apache.poi.ss.formula.FormulaType;
  28. import org.apache.poi.ss.SpreadsheetVersion;
  29. import org.apache.poi.util.LittleEndianInput;
  30. /**
  31. * @author Josh Micich
  32. */
  33. public final class TestSharedFormulaRecord extends TestCase {
  34. /**
  35. * A sample spreadsheet known to have one sheet with 4 shared formula ranges
  36. */
  37. private static final String SHARED_FORMULA_TEST_XLS = "SharedFormulaTest.xls";
  38. /**
  39. * Binary data for an encoded formula. Taken from attachment 22062 (bugzilla 45123/45421).
  40. * The shared formula is in Sheet1!C6:C21, with text "SUMPRODUCT(--(End_Acct=$C6),--(End_Bal))"
  41. * This data is found at offset 0x1A4A (within the shared formula record).
  42. * The critical thing about this formula is that it contains shared formula tokens (tRefN*,
  43. * tAreaN*) with operand class 'array'.
  44. */
  45. private static final byte[] SHARED_FORMULA_WITH_REF_ARRAYS_DATA = {
  46. 0x1A, 0x00,
  47. 0x63, 0x02, 0x00, 0x00, 0x00,
  48. 0x6C, 0x00, 0x00, 0x02, (byte)0x80, // tRefNA
  49. 0x0B,
  50. 0x15,
  51. 0x13,
  52. 0x13,
  53. 0x63, 0x03, 0x00, 0x00, 0x00,
  54. 0x15,
  55. 0x13,
  56. 0x13,
  57. 0x42, 0x02, (byte)0xE4, 0x00,
  58. };
  59. /**
  60. * The method <tt>SharedFormulaRecord.convertSharedFormulas()</tt> converts formulas from
  61. * 'shared formula' to 'single cell formula' format. It is important that token operand
  62. * classes are preserved during this transformation, because Excel may not tolerate the
  63. * incorrect encoding. The formula here is one such example (Excel displays #VALUE!).
  64. */
  65. public void testConvertSharedFormulasOperandClasses_bug45123() {
  66. LittleEndianInput in = TestcaseRecordInputStream.createLittleEndian(SHARED_FORMULA_WITH_REF_ARRAYS_DATA);
  67. int encodedLen = in.readUShort();
  68. Ptg[] sharedFormula = Ptg.readTokens(encodedLen, in);
  69. SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL97);
  70. Ptg[] convertedFormula = sf.convertSharedFormulas(sharedFormula, 100, 200);
  71. RefPtg refPtg = (RefPtg) convertedFormula[1];
  72. assertEquals("$C101", refPtg.toFormulaString());
  73. if (refPtg.getPtgClass() == Ptg.CLASS_REF) {
  74. throw new AssertionFailedError("Identified bug 45123");
  75. }
  76. confirmOperandClasses(sharedFormula, convertedFormula);
  77. }
  78. private static void confirmOperandClasses(Ptg[] originalPtgs, Ptg[] convertedPtgs) {
  79. assertEquals(originalPtgs.length, convertedPtgs.length);
  80. for (int i = 0; i < convertedPtgs.length; i++) {
  81. Ptg originalPtg = originalPtgs[i];
  82. Ptg convertedPtg = convertedPtgs[i];
  83. if (originalPtg.getPtgClass() != convertedPtg.getPtgClass()) {
  84. throw new ComparisonFailure("Different operand class for token[" + i + "]",
  85. String.valueOf(originalPtg.getPtgClass()), String.valueOf(convertedPtg.getPtgClass()));
  86. }
  87. }
  88. }
  89. public void testConvertSharedFormulas() {
  90. HSSFWorkbook wb = new HSSFWorkbook();
  91. HSSFEvaluationWorkbook fpb = HSSFEvaluationWorkbook.create(wb);
  92. Ptg[] sharedFormula, convertedFormula;
  93. SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL97);
  94. sharedFormula = FormulaParser.parse("A2", fpb, FormulaType.CELL, -1);
  95. convertedFormula = sf.convertSharedFormulas(sharedFormula, 0, 0);
  96. confirmOperandClasses(sharedFormula, convertedFormula);
  97. //conversion relative to [0,0] should return the original formula
  98. assertEquals("A2", FormulaRenderer.toFormulaString(fpb, convertedFormula));
  99. convertedFormula = sf.convertSharedFormulas(sharedFormula, 1, 0);
  100. confirmOperandClasses(sharedFormula, convertedFormula);
  101. //one row down
  102. assertEquals("A3", FormulaRenderer.toFormulaString(fpb, convertedFormula));
  103. convertedFormula = sf.convertSharedFormulas(sharedFormula, 1, 1);
  104. confirmOperandClasses(sharedFormula, convertedFormula);
  105. //one row down and one cell right
  106. assertEquals("B3", FormulaRenderer.toFormulaString(fpb, convertedFormula));
  107. sharedFormula = FormulaParser.parse("SUM(A1:C1)", fpb, FormulaType.CELL, -1);
  108. convertedFormula = sf.convertSharedFormulas(sharedFormula, 0, 0);
  109. confirmOperandClasses(sharedFormula, convertedFormula);
  110. assertEquals("SUM(A1:C1)", FormulaRenderer.toFormulaString(fpb, convertedFormula));
  111. convertedFormula = sf.convertSharedFormulas(sharedFormula, 1, 0);
  112. confirmOperandClasses(sharedFormula, convertedFormula);
  113. assertEquals("SUM(A2:C2)", FormulaRenderer.toFormulaString(fpb, convertedFormula));
  114. convertedFormula = sf.convertSharedFormulas(sharedFormula, 1, 1);
  115. confirmOperandClasses(sharedFormula, convertedFormula);
  116. assertEquals("SUM(B2:D2)", FormulaRenderer.toFormulaString(fpb, convertedFormula));
  117. }
  118. /**
  119. * Make sure that POI preserves {@link SharedFormulaRecord}s
  120. */
  121. public void testPreserveOnReserialize() {
  122. HSSFWorkbook wb;
  123. HSSFSheet sheet;
  124. HSSFCell cellB32769;
  125. HSSFCell cellC32769;
  126. // Reading directly from XLS file
  127. wb = HSSFTestDataSamples.openSampleWorkbook(SHARED_FORMULA_TEST_XLS);
  128. sheet = wb.getSheetAt(0);
  129. cellB32769 = sheet.getRow(32768).getCell(1);
  130. cellC32769 = sheet.getRow(32768).getCell(2);
  131. // check reading of formulas which are shared (two cells from a 1R x 8C range)
  132. assertEquals("B32770*2", cellB32769.getCellFormula());
  133. assertEquals("C32770*2", cellC32769.getCellFormula());
  134. confirmCellEvaluation(wb, cellB32769, 4);
  135. confirmCellEvaluation(wb, cellC32769, 6);
  136. // Confirm this example really does have SharedFormulas.
  137. // there are 3 others besides the one at A32769:H32769
  138. assertEquals(4, countSharedFormulas(sheet));
  139. // Re-serialize and check again
  140. wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
  141. sheet = wb.getSheetAt(0);
  142. cellB32769 = sheet.getRow(32768).getCell(1);
  143. cellC32769 = sheet.getRow(32768).getCell(2);
  144. assertEquals("B32770*2", cellB32769.getCellFormula());
  145. confirmCellEvaluation(wb, cellB32769, 4);
  146. assertEquals(4, countSharedFormulas(sheet));
  147. }
  148. public void testUnshareFormulaDueToChangeFormula() {
  149. HSSFWorkbook wb;
  150. HSSFSheet sheet;
  151. HSSFCell cellB32769;
  152. HSSFCell cellC32769;
  153. wb = HSSFTestDataSamples.openSampleWorkbook(SHARED_FORMULA_TEST_XLS);
  154. sheet = wb.getSheetAt(0);
  155. cellB32769 = sheet.getRow(32768).getCell(1);
  156. cellC32769 = sheet.getRow(32768).getCell(2);
  157. // Updating cell formula, causing it to become unshared
  158. cellB32769.setCellFormula("1+1");
  159. confirmCellEvaluation(wb, cellB32769, 2);
  160. // currently (Oct 2008) POI handles this by exploding the whole shared formula group
  161. assertEquals(3, countSharedFormulas(sheet)); // one less now
  162. // check that nearby cell of the same group still has the same formula
  163. assertEquals("C32770*2", cellC32769.getCellFormula());
  164. confirmCellEvaluation(wb, cellC32769, 6);
  165. }
  166. public void testUnshareFormulaDueToDelete() {
  167. HSSFWorkbook wb;
  168. HSSFSheet sheet;
  169. HSSFCell cell;
  170. final int ROW_IX = 2;
  171. // changing shared formula cell to blank
  172. wb = HSSFTestDataSamples.openSampleWorkbook(SHARED_FORMULA_TEST_XLS);
  173. sheet = wb.getSheetAt(0);
  174. assertEquals("A$1*2", sheet.getRow(ROW_IX).getCell(1).getCellFormula());
  175. cell = sheet.getRow(ROW_IX).getCell(1);
  176. cell.setCellType(HSSFCell.CELL_TYPE_BLANK);
  177. assertEquals(3, countSharedFormulas(sheet));
  178. wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
  179. sheet = wb.getSheetAt(0);
  180. assertEquals("A$1*2", sheet.getRow(ROW_IX+1).getCell(1).getCellFormula());
  181. // deleting shared formula cell
  182. wb = HSSFTestDataSamples.openSampleWorkbook(SHARED_FORMULA_TEST_XLS);
  183. sheet = wb.getSheetAt(0);
  184. assertEquals("A$1*2", sheet.getRow(ROW_IX).getCell(1).getCellFormula());
  185. cell = sheet.getRow(ROW_IX).getCell(1);
  186. sheet.getRow(ROW_IX).removeCell(cell);
  187. assertEquals(3, countSharedFormulas(sheet));
  188. wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
  189. sheet = wb.getSheetAt(0);
  190. assertEquals("A$1*2", sheet.getRow(ROW_IX+1).getCell(1).getCellFormula());
  191. }
  192. private static void confirmCellEvaluation(HSSFWorkbook wb, HSSFCell cell, double expectedValue) {
  193. HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
  194. CellValue cv = fe.evaluate(cell);
  195. assertEquals(HSSFCell.CELL_TYPE_NUMERIC, cv.getCellType());
  196. assertEquals(expectedValue, cv.getNumberValue(), 0.0);
  197. }
  198. /**
  199. * @return the number of {@link SharedFormulaRecord}s encoded for the specified sheet
  200. */
  201. private static int countSharedFormulas(HSSFSheet sheet) {
  202. Record[] records = RecordInspector.getRecords(sheet, 0);
  203. int count = 0;
  204. for (int i = 0; i < records.length; i++) {
  205. Record rec = records[i];
  206. if(rec instanceof SharedFormulaRecord) {
  207. count++;
  208. }
  209. }
  210. return count;
  211. }
  212. }