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.

TestFormulaParser.java 57KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559
  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.model;
  16. import static org.apache.poi.hssf.model.HSSFFormulaParser.parse;
  17. import static org.junit.jupiter.api.Assertions.*;
  18. import java.io.IOException;
  19. import java.util.Locale;
  20. import org.apache.poi.hssf.HSSFTestDataSamples;
  21. import org.apache.poi.hssf.record.NameRecord;
  22. import org.apache.poi.hssf.record.common.UnicodeString;
  23. import org.apache.poi.hssf.usermodel.FormulaExtractor;
  24. import org.apache.poi.hssf.usermodel.HSSFCell;
  25. import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook;
  26. import org.apache.poi.hssf.usermodel.HSSFName;
  27. import org.apache.poi.hssf.usermodel.HSSFRow;
  28. import org.apache.poi.hssf.usermodel.HSSFSheet;
  29. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  30. import org.apache.poi.hssf.usermodel.TestHSSFName;
  31. import org.apache.poi.ss.formula.FormulaParseException;
  32. import org.apache.poi.ss.formula.FormulaParser;
  33. import org.apache.poi.ss.formula.FormulaType;
  34. import org.apache.poi.ss.formula.constant.ErrorConstant;
  35. import org.apache.poi.ss.formula.ptg.*;
  36. import org.apache.poi.ss.usermodel.BaseTestBugzillaIssues;
  37. import org.apache.poi.ss.usermodel.FormulaError;
  38. import org.apache.poi.ss.usermodel.FormulaEvaluator;
  39. import org.apache.poi.ss.usermodel.Name;
  40. import org.apache.poi.util.HexRead;
  41. import org.apache.poi.util.LittleEndianByteArrayInputStream;
  42. import org.junit.jupiter.api.Test;
  43. /**
  44. * Test the low level formula parser functionality. High level tests are to
  45. * be done via usermodel/HSSFCell.setFormulaValue().
  46. */
  47. final class TestFormulaParser {
  48. /**
  49. * @return parsed token array already confirmed not {@code null}
  50. */
  51. /* package */ static Ptg[] parseFormula(String formula) {
  52. Ptg[] result = parse(formula, null);
  53. assertNotNull(result, "Ptg array should not be null");
  54. return result;
  55. }
  56. private static String toFormulaString(Ptg[] ptgs) {
  57. return HSSFFormulaParser.toFormulaString(null, ptgs);
  58. }
  59. @Test
  60. void testSimpleFormula() {
  61. confirmTokenClasses("2+2",IntPtg.class, IntPtg.class, AddPtg.class);
  62. }
  63. @Test
  64. void testFormulaWithSpace1() {
  65. confirmTokenClasses(" 2 + 2 ",IntPtg.class, IntPtg.class, AddPtg.class);
  66. }
  67. @Test
  68. void testFormulaWithSpace2() {
  69. Ptg[] ptgs = parseFormula("2+ sum( 3 , 4) ");
  70. assertEquals(5, ptgs.length);
  71. }
  72. @Test
  73. void testFormulaWithSpaceNRef() {
  74. Ptg[] ptgs = parseFormula("sum( A2:A3 )");
  75. assertEquals(2, ptgs.length);
  76. }
  77. @Test
  78. void testFormulaWithString() {
  79. Ptg[] ptgs = parseFormula("\"hello\" & \"world\" ");
  80. assertEquals(3, ptgs.length);
  81. }
  82. @Test
  83. void testTRUE() {
  84. Ptg[] ptgs = parseFormula("TRUE");
  85. assertEquals(1, ptgs.length);
  86. BoolPtg flag = (BoolPtg) ptgs[0];
  87. assertTrue(flag.getValue());
  88. }
  89. @Test
  90. void testSumIf() {
  91. Ptg[] ptgs = parseFormula("SUMIF(A1:A5,\">4000\",B1:B5)");
  92. assertEquals(4, ptgs.length);
  93. }
  94. /**
  95. * Bug Reported by xt-jens.riis@nokia.com (Jens Riis)
  96. * Refers to Bug <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=17582">#17582</a>
  97. *
  98. */
  99. @Test
  100. void testNonAlphaFormula() {
  101. Ptg[] ptgs = parseFormula("\"TOTAL[\"&F3&\"]\"");
  102. confirmTokenClasses(ptgs, StringPtg.class, RefPtg.class, ConcatPtg.class, StringPtg.class, ConcatPtg.class);
  103. assertEquals("TOTAL[", ((StringPtg)ptgs[0]).getValue());
  104. }
  105. @Test
  106. void testMacroFunction() throws IOException {
  107. // testNames.xls contains a VB function called 'myFunc'
  108. final String testFile = "testNames.xls";
  109. try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(testFile)) {
  110. HSSFEvaluationWorkbook book = HSSFEvaluationWorkbook.create(wb);
  111. //Expected ptg stack: [NamePtg(myFunc), StringPtg(arg), (additional operands go here...), FunctionPtg(myFunc)]
  112. Ptg[] ptg = FormulaParser.parse("myFunc(\"arg\")", book, FormulaType.CELL, -1);
  113. assertEquals(3, ptg.length);
  114. // the name gets encoded as the first operand on the stack
  115. NamePtg tname = (NamePtg) ptg[0];
  116. assertEquals("myFunc", tname.toFormulaString(book));
  117. // the function's arguments are pushed onto the stack from left-to-right as OperandPtgs
  118. StringPtg arg = (StringPtg) ptg[1];
  119. assertEquals("arg", arg.getValue());
  120. // The external FunctionPtg is the last Ptg added to the stack
  121. // During formula evaluation, this Ptg pops off the the appropriate number of
  122. // arguments (getNumberOfOperands()) and pushes the result on the stack
  123. AbstractFunctionPtg tfunc = (AbstractFunctionPtg) ptg[2]; //FuncVarPtg
  124. assertTrue(tfunc.isExternalFunction());
  125. // confirm formula parsing is case-insensitive
  126. FormulaParser.parse("mYfUnC(\"arg\")", book, FormulaType.CELL, -1);
  127. // confirm formula parsing doesn't care about argument count or type
  128. // this should only throw an error when evaluating the formula.
  129. FormulaParser.parse("myFunc()", book, FormulaType.CELL, -1);
  130. FormulaParser.parse("myFunc(\"arg\", 0, TRUE)", book, FormulaType.CELL, -1);
  131. // A completely unknown formula name (not saved in workbook) should still be parseable and renderable
  132. // but will throw an NotImplementedFunctionException or return a #NAME? error value if evaluated.
  133. FormulaParser.parse("yourFunc(\"arg\")", book, FormulaType.CELL, -1);
  134. // Verify that myFunc and yourFunc were successfully added to Workbook names
  135. try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb)) {
  136. // HSSFWorkbook/EXCEL97-specific side-effects user-defined function names must be added to Workbook's defined names in order to be saved.
  137. HSSFName myFunc = wb2.getName("myFunc");
  138. assertNotNull(myFunc);
  139. assertEqualsIgnoreCase("myFunc", myFunc.getNameName());
  140. HSSFName yourFunc = wb2.getName("yourFunc");
  141. assertNotNull(yourFunc);
  142. assertEqualsIgnoreCase("yourFunc", yourFunc.getNameName());
  143. }
  144. }
  145. }
  146. private static void assertEqualsIgnoreCase(String expected, String actual) {
  147. assertEquals(expected.toLowerCase(Locale.ROOT), actual.toLowerCase(Locale.ROOT));
  148. }
  149. @Test
  150. void testEmbeddedSlash() {
  151. confirmTokenClasses("HYPERLINK(\"http://www.jakarta.org\",\"Jakarta\")",
  152. StringPtg.class, StringPtg.class, FuncVarPtg.class);
  153. }
  154. @Test
  155. void testConcatenate() {
  156. confirmTokenClasses("CONCATENATE(\"first\",\"second\")",
  157. StringPtg.class, StringPtg.class, FuncVarPtg.class);
  158. }
  159. @Test
  160. void testWorksheetReferences() throws IOException {
  161. try (HSSFWorkbook wb = new HSSFWorkbook()) {
  162. HSSFSheet sheet1 = wb.createSheet("NoQuotesNeeded");
  163. sheet1.createRow(0).createCell(0).setCellValue("NoQuotesNeeded");
  164. HSSFSheet sheet2 = wb.createSheet("Quotes Needed Here &#$@");
  165. sheet2.createRow(0).createCell(0).setCellValue("Quotes Needed Here &#$@");
  166. HSSFSheet sheet = wb.createSheet("Test");
  167. HSSFRow row = sheet.createRow(0);
  168. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  169. HSSFCell cell;
  170. String act;
  171. cell = row.createCell(0);
  172. cell.setCellFormula("NoQuotesNeeded!A1");
  173. act = evaluator.evaluate(cell).getStringValue();
  174. assertEquals("NoQuotesNeeded", act);
  175. cell = row.createCell(1);
  176. cell.setCellFormula("'Quotes Needed Here &#$@'!A1");
  177. act = evaluator.evaluate(cell).getStringValue();
  178. assertEquals("Quotes Needed Here &#$@", act);
  179. }
  180. }
  181. @Test
  182. void testUnaryMinus() {
  183. confirmTokenClasses("-A1", RefPtg.class, UnaryMinusPtg.class);
  184. }
  185. @Test
  186. void testUnaryPlus() {
  187. confirmTokenClasses("+A1", RefPtg.class, UnaryPlusPtg.class);
  188. }
  189. /**
  190. * There may be multiple ways to encode an expression involving {@link UnaryPlusPtg}
  191. * or {@link UnaryMinusPtg}. These may be perfectly equivalent from a formula
  192. * evaluation perspective, or formula rendering. However, differences in the way
  193. * POI encodes formulas may cause unnecessary confusion. These non-critical tests
  194. * check that POI follows the same encoding rules as Excel.
  195. */
  196. @Test
  197. void testExactEncodingOfUnaryPlusAndMinus() {
  198. // as tested in Excel:
  199. confirmUnary("-3", -3, NumberPtg.class);
  200. confirmUnary("--4", -4, NumberPtg.class, UnaryMinusPtg.class);
  201. confirmUnary("+++5", 5, IntPtg.class, UnaryPlusPtg.class, UnaryPlusPtg.class);
  202. confirmUnary("++-6", -6, NumberPtg.class, UnaryPlusPtg.class, UnaryPlusPtg.class);
  203. // Spaces muck things up a bit. It would be clearer why the following cases are
  204. // reasonable if POI encoded tAttrSpace in the right places.
  205. // Otherwise these differences look capricious.
  206. confirmUnary("+ 12", 12, IntPtg.class, UnaryPlusPtg.class);
  207. confirmUnary("- 13", 13, IntPtg.class, UnaryMinusPtg.class);
  208. }
  209. private static void confirmUnary(String formulaText, double val, Class<?>...expectedTokenTypes) {
  210. Ptg[] ptgs = parseFormula(formulaText);
  211. confirmTokenClasses(ptgs, expectedTokenTypes);
  212. Ptg ptg0 = ptgs[0];
  213. if (ptg0 instanceof IntPtg) {
  214. IntPtg intPtg = (IntPtg) ptg0;
  215. assertEquals((int)val, intPtg.getValue());
  216. } else if (ptg0 instanceof NumberPtg) {
  217. NumberPtg numberPtg = (NumberPtg) ptg0;
  218. assertEquals(val, numberPtg.getValue(), 0.0);
  219. } else {
  220. fail("bad ptg0 " + ptg0);
  221. }
  222. }
  223. @Test
  224. void testLeadingSpaceInString() {
  225. String value = " hi ";
  226. Ptg[] ptgs = parseFormula("\"" + value + "\"");
  227. confirmTokenClasses(ptgs, StringPtg.class);
  228. assertEquals(((StringPtg) ptgs[0]).getValue(), value, "ptg0 contains exact value");
  229. }
  230. @Test
  231. void testLookupAndMatchFunctionArgs() {
  232. Ptg[] ptgs = parseFormula("lookup(A1, A3:A52, B3:B52)");
  233. confirmTokenClasses(ptgs, RefPtg.class, AreaPtg.class, AreaPtg.class, FuncVarPtg.class);
  234. assertEquals(Ptg.CLASS_VALUE, ptgs[0].getPtgClass(), "ptg0 has Value class");
  235. ptgs = parseFormula("match(A1, A3:A52)");
  236. confirmTokenClasses(ptgs, RefPtg.class, AreaPtg.class, FuncVarPtg.class);
  237. assertEquals(Ptg.CLASS_VALUE, ptgs[0].getPtgClass(), "ptg0 has Value class");
  238. }
  239. /** bug 33160*/
  240. @Test
  241. void testLargeInt() {
  242. confirmTokenClasses("40", IntPtg.class);
  243. confirmTokenClasses("40000", IntPtg.class);
  244. }
  245. /** bug 33160 */
  246. @Test
  247. void testSimpleLongFormula() {
  248. confirmTokenClasses("40000/2", IntPtg.class, IntPtg.class, DividePtg.class);
  249. }
  250. /** bug 35027, underscore in sheet name */
  251. @Test
  252. void testUnderscore() throws IOException {
  253. try (HSSFWorkbook wb = new HSSFWorkbook()) {
  254. HSSFSheet sheet1 = wb.createSheet("Cash_Flow");
  255. sheet1.createRow(0).createCell(0).setCellValue("Cash_Flow");
  256. HSSFSheet sheet = wb.createSheet("Test");
  257. HSSFRow row = sheet.createRow(0);
  258. HSSFCell cell;
  259. cell = row.createCell(0);
  260. cell.setCellFormula("Cash_Flow!A1");
  261. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  262. String act = evaluator.evaluate(cell).getStringValue();
  263. assertEquals("Cash_Flow", act);
  264. }
  265. }
  266. /** bug 49725, defined names with underscore */
  267. @Test
  268. void testNamesWithUnderscore() throws IOException {
  269. HSSFWorkbook wb = new HSSFWorkbook(); //or new XSSFWorkbook();
  270. HSSFSheet sheet = wb.createSheet("NamesWithUnderscore");
  271. HSSFName nm;
  272. nm = wb.createName();
  273. nm.setNameName("DA6_LEO_WBS_Number");
  274. nm.setRefersToFormula("33");
  275. nm = wb.createName();
  276. nm.setNameName("DA6_LEO_WBS_Name");
  277. nm.setRefersToFormula("33");
  278. nm = wb.createName();
  279. nm.setNameName("A1_");
  280. nm.setRefersToFormula("22");
  281. nm = wb.createName();
  282. nm.setNameName("_A1");
  283. nm.setRefersToFormula("11");
  284. nm = wb.createName();
  285. nm.setNameName("A_1");
  286. nm.setRefersToFormula("44");
  287. nm = wb.createName();
  288. nm.setNameName("A_1_");
  289. nm.setRefersToFormula("44");
  290. HSSFRow row = sheet.createRow(0);
  291. HSSFCell cell = row.createCell(0);
  292. cell.setCellFormula("DA6_LEO_WBS_Number*2");
  293. assertEquals("DA6_LEO_WBS_Number*2", cell.getCellFormula());
  294. cell.setCellFormula("(A1_*_A1+A_1)/A_1_");
  295. assertEquals("(A1_*_A1+A_1)/A_1_", cell.getCellFormula());
  296. cell.setCellFormula("INDEX(DA6_LEO_WBS_Name,MATCH($A3,DA6_LEO_WBS_Number,0))");
  297. assertEquals("INDEX(DA6_LEO_WBS_Name,MATCH($A3,DA6_LEO_WBS_Number,0))", cell.getCellFormula());
  298. wb.close();
  299. }
  300. // bug 38396 : Formula with exponential numbers not parsed correctly.
  301. @Test
  302. void testExponentialParsing() {
  303. confirmTokenClasses("1.3E21/2", NumberPtg.class, IntPtg.class, DividePtg.class);
  304. confirmTokenClasses("1322E21/2", NumberPtg.class, IntPtg.class, DividePtg.class);
  305. confirmTokenClasses("1.3E1/2", NumberPtg.class, IntPtg.class, DividePtg.class);
  306. }
  307. @Test
  308. void testExponentialInSheet() throws IOException {
  309. HSSFWorkbook wb = new HSSFWorkbook();
  310. wb.createSheet("Cash_Flow");
  311. HSSFSheet sheet = wb.createSheet("Test");
  312. HSSFRow row = sheet.createRow(0);
  313. HSSFCell cell = row.createCell(0);
  314. String formula;
  315. cell.setCellFormula("1.3E21/3");
  316. formula = cell.getCellFormula();
  317. assertEquals("1.3E+21/3", formula);
  318. cell.setCellFormula("-1.3E21/3");
  319. formula = cell.getCellFormula();
  320. assertEquals("-1.3E+21/3", formula);
  321. cell.setCellFormula("1322E21/3");
  322. formula = cell.getCellFormula();
  323. assertEquals("1.322E+24/3", formula);
  324. cell.setCellFormula("-1322E21/3");
  325. formula = cell.getCellFormula();
  326. assertEquals("-1.322E+24/3", formula);
  327. cell.setCellFormula("1.3E1/3");
  328. formula = cell.getCellFormula();
  329. assertEquals("13/3", formula);
  330. cell.setCellFormula("-1.3E1/3");
  331. formula = cell.getCellFormula();
  332. assertEquals("-13/3", formula);
  333. cell.setCellFormula("1.3E-4/3");
  334. formula = cell.getCellFormula();
  335. assertEquals("0.00013/3", formula);
  336. cell.setCellFormula("-1.3E-4/3");
  337. formula = cell.getCellFormula();
  338. assertEquals("-0.00013/3", formula);
  339. cell.setCellFormula("13E-15/3");
  340. formula = cell.getCellFormula();
  341. assertEquals("0.000000000000013/3", formula);
  342. cell.setCellFormula("-13E-15/3");
  343. formula = cell.getCellFormula();
  344. assertEquals("-0.000000000000013/3", formula);
  345. cell.setCellFormula("1.3E3/3");
  346. formula = cell.getCellFormula();
  347. assertEquals("1300/3", formula);
  348. cell.setCellFormula("-1.3E3/3");
  349. formula = cell.getCellFormula();
  350. assertEquals("-1300/3", formula);
  351. cell.setCellFormula("1300000000000000/3");
  352. formula = cell.getCellFormula();
  353. assertEquals("1300000000000000/3", formula);
  354. cell.setCellFormula("-1300000000000000/3");
  355. formula = cell.getCellFormula();
  356. assertEquals("-1300000000000000/3", formula);
  357. cell.setCellFormula("-10E-1/3.1E2*4E3/3E4");
  358. formula = cell.getCellFormula();
  359. assertEquals("-1/310*4000/30000", formula);
  360. wb.close();
  361. }
  362. @Test
  363. void testNumbers() throws IOException {
  364. HSSFWorkbook wb = new HSSFWorkbook();
  365. wb.createSheet("Cash_Flow");
  366. HSSFSheet sheet = wb.createSheet("Test");
  367. HSSFRow row = sheet.createRow(0);
  368. HSSFCell cell = row.createCell(0);
  369. String formula;
  370. // starts from decimal point
  371. cell.setCellFormula(".1");
  372. formula = cell.getCellFormula();
  373. assertEquals("0.1", formula);
  374. cell.setCellFormula("+.1");
  375. formula = cell.getCellFormula();
  376. assertEquals("0.1", formula);
  377. cell.setCellFormula("-.1");
  378. formula = cell.getCellFormula();
  379. assertEquals("-0.1", formula);
  380. // has exponent
  381. cell.setCellFormula("10E1");
  382. formula = cell.getCellFormula();
  383. assertEquals("100", formula);
  384. cell.setCellFormula("10E+1");
  385. formula = cell.getCellFormula();
  386. assertEquals("100", formula);
  387. cell.setCellFormula("10E-1");
  388. formula = cell.getCellFormula();
  389. assertEquals("1", formula);
  390. wb.close();
  391. }
  392. @Test
  393. void testRanges() throws IOException {
  394. HSSFWorkbook wb = new HSSFWorkbook();
  395. wb.createSheet("Cash_Flow");
  396. HSSFSheet sheet = wb.createSheet("Test");
  397. HSSFRow row = sheet.createRow(0);
  398. HSSFCell cell = row.createCell(0);
  399. String formula;
  400. cell.setCellFormula("A1.A2");
  401. formula = cell.getCellFormula();
  402. assertEquals("A1:A2", formula);
  403. cell.setCellFormula("A1..A2");
  404. formula = cell.getCellFormula();
  405. assertEquals("A1:A2", formula);
  406. cell.setCellFormula("A1...A2");
  407. formula = cell.getCellFormula();
  408. assertEquals("A1:A2", formula);
  409. wb.close();
  410. }
  411. @Test
  412. void testMultiSheetReference() throws IOException {
  413. HSSFWorkbook wb = new HSSFWorkbook();
  414. wb.createSheet("Cash_Flow");
  415. wb.createSheet("Test Sheet");
  416. HSSFSheet sheet = wb.createSheet("Test");
  417. HSSFRow row = sheet.createRow(0);
  418. HSSFCell cell = row.createCell(0);
  419. String formula;
  420. // References to a single cell:
  421. // One sheet
  422. cell.setCellFormula("Cash_Flow!A1");
  423. formula = cell.getCellFormula();
  424. assertEquals("Cash_Flow!A1", formula);
  425. // Then the other
  426. cell.setCellFormula("'Test Sheet'!A1");
  427. formula = cell.getCellFormula();
  428. assertEquals("'Test Sheet'!A1", formula);
  429. // Now both
  430. cell.setCellFormula("'Cash_Flow:Test Sheet'!A1");
  431. formula = cell.getCellFormula();
  432. assertEquals("'Cash_Flow:Test Sheet'!A1", formula);
  433. // References to a range (area) of cells:
  434. // One sheet
  435. cell.setCellFormula("Cash_Flow!A1:B2");
  436. formula = cell.getCellFormula();
  437. assertEquals("Cash_Flow!A1:B2", formula);
  438. // Then the other
  439. cell.setCellFormula("'Test Sheet'!A1:B2");
  440. formula = cell.getCellFormula();
  441. assertEquals("'Test Sheet'!A1:B2", formula);
  442. // Now both
  443. cell.setCellFormula("'Cash_Flow:Test Sheet'!A1:B2");
  444. formula = cell.getCellFormula();
  445. assertEquals("'Cash_Flow:Test Sheet'!A1:B2", formula);
  446. wb.close();
  447. }
  448. /**
  449. * Test for bug observable at svn revision 618865 (5-Feb-2008)<br>
  450. * a formula consisting of a single no-arg function got rendered without the function braces
  451. */
  452. @Test
  453. void testToFormulaStringZeroArgFunction() throws IOException {
  454. HSSFWorkbook book = new HSSFWorkbook();
  455. Ptg[] ptgs = {
  456. FuncPtg.create(10),
  457. };
  458. assertEquals("NA()", HSSFFormulaParser.toFormulaString(book, ptgs));
  459. book.close();
  460. }
  461. @Test
  462. void testPercent() {
  463. confirmTokenClasses("5%", IntPtg.class, PercentPtg.class);
  464. // spaces OK
  465. confirmTokenClasses(" 250 % ", IntPtg.class, PercentPtg.class);
  466. // double percent OK
  467. confirmTokenClasses("12345.678%%", NumberPtg.class, PercentPtg.class, PercentPtg.class);
  468. // percent of a bracketed expression
  469. confirmTokenClasses("(A1+35)%*B1%", RefPtg.class, IntPtg.class, AddPtg.class, ParenthesisPtg.class,
  470. PercentPtg.class, RefPtg.class, PercentPtg.class, MultiplyPtg.class);
  471. // percent of a text quantity
  472. confirmTokenClasses("\"8.75\"%", StringPtg.class, PercentPtg.class);
  473. // percent to the power of
  474. confirmTokenClasses("50%^3", IntPtg.class, PercentPtg.class, IntPtg.class, PowerPtg.class);
  475. // things that parse OK but would *evaluate* to an error
  476. confirmTokenClasses("\"abc\"%", StringPtg.class, PercentPtg.class);
  477. confirmTokenClasses("#N/A%", ErrPtg.class, PercentPtg.class);
  478. }
  479. /**
  480. * Tests combinations of various operators in the absence of brackets
  481. */
  482. @Test
  483. void testPrecedenceAndAssociativity() {
  484. // TRUE=TRUE=2=2 evaluates to FALSE
  485. confirmTokenClasses("TRUE=TRUE=2=2", BoolPtg.class, BoolPtg.class, EqualPtg.class,
  486. IntPtg.class, EqualPtg.class, IntPtg.class, EqualPtg.class);
  487. // 2^3^2 evaluates to 64 not 512
  488. confirmTokenClasses("2^3^2", IntPtg.class, IntPtg.class, PowerPtg.class,
  489. IntPtg.class, PowerPtg.class);
  490. // "abc" & 2 + 3 & "def" evaluates to "abc5def"
  491. confirmTokenClasses("\"abc\"&2+3&\"def\"", StringPtg.class, IntPtg.class, IntPtg.class,
  492. AddPtg.class, ConcatPtg.class, StringPtg.class, ConcatPtg.class);
  493. // (1 / 2) - (3 * 4)
  494. confirmTokenClasses("1/2-3*4", IntPtg.class, IntPtg.class, DividePtg.class,
  495. IntPtg.class, IntPtg.class, MultiplyPtg.class, SubtractPtg.class);
  496. // 2 * (2^2)
  497. // NOT: (2 *2) ^ 2 -> int int multiply int power
  498. confirmTokenClasses("2*2^2", IntPtg.class, IntPtg.class, IntPtg.class, PowerPtg.class, MultiplyPtg.class);
  499. // 2^200% -> 2 not 1.6E58
  500. confirmTokenClasses("2^200%", IntPtg.class, IntPtg.class, PercentPtg.class, PowerPtg.class);
  501. }
  502. /* package */ static Ptg[] confirmTokenClasses(String formula, Class<?>...expectedClasses) {
  503. Ptg[] ptgs = parseFormula(formula);
  504. confirmTokenClasses(ptgs, expectedClasses);
  505. return ptgs;
  506. }
  507. private static void confirmTokenClasses(Ptg[] ptgs, Class<?>...expectedClasses) {
  508. assertEquals(expectedClasses.length, ptgs.length);
  509. for (int i = 0; i < expectedClasses.length; i++) {
  510. assertSame(expectedClasses[i], ptgs[i].getClass(),
  511. "difference at token[" + i + "]: expected ("
  512. + expectedClasses[i].getName() + ") but got ("
  513. + ptgs[i].getClass().getName() + ")");
  514. }
  515. }
  516. @Test
  517. void testPower() {
  518. confirmTokenClasses("2^5", IntPtg.class, IntPtg.class, PowerPtg.class);
  519. }
  520. private static Ptg parseSingleToken(String formula, Class<? extends Ptg> ptgClass) {
  521. Ptg[] ptgs = parseFormula(formula);
  522. assertEquals(1, ptgs.length);
  523. Ptg result = ptgs[0];
  524. assertSame(ptgClass, result.getClass());
  525. return result;
  526. }
  527. @Test
  528. void testParseNumber() {
  529. IntPtg ip;
  530. // bug 33160
  531. ip = (IntPtg) parseSingleToken("40", IntPtg.class);
  532. assertEquals(40, ip.getValue());
  533. ip = (IntPtg) parseSingleToken("40000", IntPtg.class);
  534. assertEquals(40000, ip.getValue());
  535. // check the upper edge of the IntPtg range:
  536. ip = (IntPtg) parseSingleToken("65535", IntPtg.class);
  537. assertEquals(65535, ip.getValue());
  538. NumberPtg np = (NumberPtg) parseSingleToken("65536", NumberPtg.class);
  539. assertEquals(65536, np.getValue(), 0);
  540. np = (NumberPtg) parseSingleToken("65534.6", NumberPtg.class);
  541. assertEquals(65534.6, np.getValue(), 0);
  542. }
  543. @Test
  544. void testMissingArgs() {
  545. confirmTokenClasses("if(A1, ,C1)",
  546. RefPtg.class,
  547. AttrPtg.class, // tAttrIf
  548. MissingArgPtg.class,
  549. AttrPtg.class, // tAttrSkip
  550. RefPtg.class,
  551. AttrPtg.class, // tAttrSkip
  552. FuncVarPtg.class
  553. );
  554. confirmTokenClasses("counta( , A1:B2, )", MissingArgPtg.class, AreaPtg.class, MissingArgPtg.class,
  555. FuncVarPtg.class);
  556. }
  557. @Test
  558. void testParseErrorLiterals() {
  559. confirmParseErrorLiteral(ErrPtg.NULL_INTERSECTION, "#NULL!");
  560. confirmParseErrorLiteral(ErrPtg.DIV_ZERO, "#DIV/0!");
  561. confirmParseErrorLiteral(ErrPtg.VALUE_INVALID, "#VALUE!");
  562. confirmParseErrorLiteral(ErrPtg.REF_INVALID, "#REF!");
  563. confirmParseErrorLiteral(ErrPtg.NAME_INVALID, "#NAME?");
  564. confirmParseErrorLiteral(ErrPtg.NUM_ERROR, "#NUM!");
  565. confirmParseErrorLiteral(ErrPtg.N_A, "#N/A");
  566. parseFormula("HLOOKUP(F7,#REF!,G7,#REF!)");
  567. }
  568. private static void confirmParseErrorLiteral(ErrPtg expectedToken, String formula) {
  569. assertEquals(expectedToken, parseSingleToken(formula, ErrPtg.class));
  570. }
  571. /**
  572. * To aid readability the parameters have been encoded with single quotes instead of double
  573. * quotes. This method converts single quotes to double quotes before performing the parse
  574. * and result check.
  575. */
  576. private static void confirmStringParse(String singleQuotedValue) {
  577. // formula: internal quotes become double double, surround with double quotes
  578. String formula = '"' + singleQuotedValue.replaceAll("'", "\"\"") + '"';
  579. String expectedValue = singleQuotedValue.replace('\'', '"');
  580. StringPtg sp = (StringPtg) parseSingleToken(formula, StringPtg.class);
  581. assertEquals(expectedValue, sp.getValue());
  582. }
  583. @Test
  584. void testParseStringLiterals_bug28754() throws IOException {
  585. StringPtg sp;
  586. try {
  587. sp = (StringPtg) parseSingleToken("\"test\"\"ing\"", StringPtg.class);
  588. } catch (RuntimeException e) {
  589. if(e.getMessage().startsWith("Cannot Parse")) {
  590. fail("Identified bug 28754a");
  591. }
  592. throw e;
  593. }
  594. assertEquals("test\"ing", sp.getValue());
  595. try (HSSFWorkbook wb = new HSSFWorkbook()) {
  596. HSSFSheet sheet = wb.createSheet();
  597. wb.setSheetName(0, "Sheet1");
  598. HSSFRow row = sheet.createRow(0);
  599. HSSFCell cell = row.createCell(0);
  600. cell.setCellFormula("right(\"test\"\"ing\", 3)");
  601. String actualCellFormula = cell.getCellFormula();
  602. assertNotEquals("RIGHT(\"test\"ing\",3)", actualCellFormula, "Identified bug 28754b");
  603. assertEquals("RIGHT(\"test\"\"ing\",3)", actualCellFormula);
  604. }
  605. }
  606. @Test
  607. void testParseStringLiterals() {
  608. confirmStringParse("goto considered harmful");
  609. confirmStringParse("goto 'considered' harmful");
  610. confirmStringParse("");
  611. confirmStringParse("'");
  612. confirmStringParse("''");
  613. confirmStringParse("' '");
  614. confirmStringParse(" ' ");
  615. }
  616. @Test
  617. void testParseSumIfSum() {
  618. String formulaString;
  619. Ptg[] ptgs;
  620. ptgs = parseFormula("sum(5, 2, if(3>2, sum(A1:A2), 6))");
  621. formulaString = toFormulaString(ptgs);
  622. assertEquals("SUM(5,2,IF(3>2,SUM(A1:A2),6))", formulaString);
  623. ptgs = parseFormula("if(1<2,sum(5, 2, if(3>2, sum(A1:A2), 6)),4)");
  624. formulaString = toFormulaString(ptgs);
  625. assertEquals("IF(1<2,SUM(5,2,IF(3>2,SUM(A1:A2),6)),4)", formulaString);
  626. }
  627. @Test
  628. void testParserErrors() {
  629. parseExpectedException(" 12 . 345 ");
  630. parseExpectedException("1 .23 ");
  631. parseExpectedException("sum(#NAME)");
  632. parseExpectedException("1 + #N / A * 2");
  633. parseExpectedException("#value?");
  634. parseExpectedException("#DIV/ 0+2");
  635. parseExpectedException("IF(TRUE)");
  636. parseExpectedException("countif(A1:B5, C1, D1)");
  637. parseExpectedException("(");
  638. parseExpectedException(")");
  639. parseExpectedException("+");
  640. parseExpectedException("42+");
  641. parseExpectedException("IF(");
  642. }
  643. private static void parseExpectedException(String formula) {
  644. FormulaParseException e = assertThrows(FormulaParseException.class, () -> parseFormula(formula));
  645. assertNotNull(e.getMessage());
  646. }
  647. @Test
  648. void testSetFormulaWithRowBeyond32768_Bug44539() throws IOException {
  649. HSSFWorkbook wb = new HSSFWorkbook();
  650. HSSFSheet sheet = wb.createSheet();
  651. wb.setSheetName(0, "Sheet1");
  652. HSSFRow row = sheet.createRow(0);
  653. HSSFCell cell = row.createCell(0);
  654. cell.setCellFormula("SUM(A32769:A32770)");
  655. assertNotEquals("SUM(A-32767:A-32766)", cell.getCellFormula(), "Identified bug 44539");
  656. assertEquals("SUM(A32769:A32770)", cell.getCellFormula());
  657. wb.close();
  658. }
  659. @Test
  660. void testSpaceAtStartOfFormula() {
  661. // Simulating cell formula of "= 4" (note space)
  662. // The same Ptg array can be observed if an excel file is saved with that exact formula
  663. AttrPtg spacePtg = AttrPtg.createSpace(AttrPtg.SpaceType.SPACE_BEFORE, 1);
  664. Ptg[] ptgs = { spacePtg, new IntPtg(4), };
  665. String formulaString;
  666. try {
  667. formulaString = toFormulaString(ptgs);
  668. } catch (IllegalStateException e) {
  669. if(e.getMessage().equalsIgnoreCase("too much stuff left on the stack")) {
  670. fail("Identified bug 44609");
  671. }
  672. // else some unexpected error
  673. throw e;
  674. }
  675. // FormulaParser strips spaces anyway
  676. assertEquals("4", formulaString);
  677. ptgs = new Ptg[] { new IntPtg(3), spacePtg, new IntPtg(4), spacePtg, AddPtg.instance, };
  678. formulaString = toFormulaString(ptgs);
  679. assertEquals("3+4", formulaString);
  680. }
  681. /**
  682. * Checks some internal error detecting logic ('stack underflow error' in toFormulaString)
  683. */
  684. @Test
  685. void testTooFewOperandArgs() {
  686. // Simulating badly encoded cell formula of "=/1"
  687. // Not sure if Excel could ever produce this
  688. Ptg[] ptgs = {
  689. // Excel would probably have put tMissArg here
  690. new IntPtg(1),
  691. DividePtg.instance,
  692. };
  693. IllegalStateException e = assertThrows(IllegalStateException.class, () -> toFormulaString(ptgs));
  694. assertTrue(e.getMessage().startsWith("Too few arguments supplied to operation"));
  695. }
  696. /**
  697. * Make sure that POI uses the right Func Ptg when encoding formulas. Functions with variable
  698. * number of args should get FuncVarPtg, functions with fixed args should get FuncPtg.<p>
  699. *
  700. * Prior to the fix for bug 44675 POI would encode FuncVarPtg for all functions. In many cases
  701. * Excel tolerates the wrong Ptg and evaluates the formula OK (e.g. SIN), but in some cases
  702. * (e.g. COUNTIF) Excel fails to evaluate the formula, giving '#VALUE!' instead.
  703. */
  704. @Test
  705. void testFuncPtgSelection() {
  706. Ptg[] ptgs = parseFormula("countif(A1:A2, 1)");
  707. assertEquals(3, ptgs.length);
  708. assertFalse(ptgs[2] instanceof FuncVarPtg, "Identified bug 44675");
  709. confirmTokenClasses(ptgs, AreaPtg.class, IntPtg.class, FuncPtg.class);
  710. confirmTokenClasses("sin(1)", IntPtg.class, FuncPtg.class);
  711. }
  712. @Test
  713. void testWrongNumberOfFunctionArgs() throws IOException {
  714. confirmArgCountMsg("sin()", "Too few arguments to function 'SIN'. Expected 1 but got 0.");
  715. confirmArgCountMsg("countif(1, 2, 3, 4)", "Too many arguments to function 'COUNTIF'. Expected 2 but got 4.");
  716. confirmArgCountMsg("index(1, 2, 3, 4, 5, 6)", "Too many arguments to function 'INDEX'. At most 4 were expected but got 6.");
  717. confirmArgCountMsg("vlookup(1, 2)", "Too few arguments to function 'VLOOKUP'. At least 3 were expected but got 2.");
  718. }
  719. private static void confirmArgCountMsg(String formula, String expectedMessage) throws IOException {
  720. try (HSSFWorkbook book = new HSSFWorkbook()) {
  721. FormulaParseException e = assertThrows(FormulaParseException.class, () -> parse(formula, book));
  722. confirmParseException(e, expectedMessage);
  723. }
  724. }
  725. @Test
  726. void testParseErrorExpectedMsg() {
  727. FormulaParseException e;
  728. e = assertThrows(FormulaParseException.class, () -> parseFormula("round(3.14;2)"));
  729. confirmParseException(e, "Parse error near char 10 ';' in specified formula 'round(3.14;2)'. Expected ',' or ')'");
  730. e = assertThrows(FormulaParseException.class, () -> parseFormula(" =2+2"));
  731. confirmParseException(e, "The specified formula ' =2+2' starts with an equals sign which is not allowed.");
  732. }
  733. /**
  734. * this function name has a dot in it.
  735. */
  736. @Test
  737. void testParseErrorTypeFunction() {
  738. Ptg[] ptgs;
  739. try {
  740. ptgs = parseFormula("error.type(A1)");
  741. } catch (IllegalArgumentException e) {
  742. if (e.getMessage().equals("Invalid Formula cell reference: 'error'")) {
  743. fail("Identified bug 45334");
  744. }
  745. throw e;
  746. }
  747. confirmTokenClasses(ptgs, RefPtg.class, FuncPtg.class);
  748. assertEquals("ERROR.TYPE", ((FuncPtg) ptgs[1]).getName());
  749. }
  750. @Test
  751. void testNamedRangeThatLooksLikeCell() throws IOException {
  752. try (HSSFWorkbook wb = new HSSFWorkbook()) {
  753. HSSFSheet sheet = wb.createSheet("Sheet1");
  754. HSSFName name = wb.createName();
  755. name.setRefersToFormula("Sheet1!B1");
  756. name.setNameName("pfy1");
  757. Ptg[] ptgs;
  758. try {
  759. ptgs = parse("count(pfy1)", wb);
  760. } catch (IllegalArgumentException e) {
  761. if (e.getMessage().equals("Specified colIx (1012) is out of range")) {
  762. fail("Identified bug 45354");
  763. }
  764. throw e;
  765. }
  766. confirmTokenClasses(ptgs, NamePtg.class, FuncVarPtg.class);
  767. HSSFCell cell = sheet.createRow(0).createCell(0);
  768. cell.setCellFormula("count(pfy1)");
  769. assertEquals("COUNT(pfy1)", cell.getCellFormula());
  770. FormulaParseException e = assertThrows(FormulaParseException.class, () -> cell.setCellFormula("count(pf1)"));
  771. confirmParseException(e, "Specified named range 'pf1' does not exist in the current workbook.");
  772. cell.setCellFormula("count(fp1)"); // plain cell ref, col is in range
  773. }
  774. }
  775. @Test
  776. void testParseAreaRefHighRow_bug45358() throws IOException {
  777. Ptg[] ptgs;
  778. AreaI aptg;
  779. HSSFWorkbook book = new HSSFWorkbook();
  780. book.createSheet("Sheet1");
  781. ptgs = parse("Sheet1!A10:A40000", book);
  782. aptg = (AreaI) ptgs[0];
  783. assertNotEquals(-25537, aptg.getLastRow(), "Identified bug 45358");
  784. assertEquals(39999, aptg.getLastRow());
  785. ptgs = parse("Sheet1!A10:A65536", book);
  786. aptg = (AreaI) ptgs[0];
  787. assertEquals(65535, aptg.getLastRow());
  788. // plain area refs should be ok too
  789. ptgs = parseFormula("A10:A65536");
  790. aptg = (AreaI) ptgs[0];
  791. assertEquals(65535, aptg.getLastRow());
  792. book.close();
  793. }
  794. @Test
  795. void testParseArray() {
  796. Ptg[] ptgs;
  797. ptgs = parseFormula("mode({1,2,2,#REF!;FALSE,3,3,2})");
  798. confirmTokenClasses(ptgs, ArrayPtg.class, FuncVarPtg.class);
  799. assertEquals("{1,2,2,#REF!;FALSE,3,3,2}", ptgs[0].toFormulaString());
  800. ArrayPtg aptg = (ArrayPtg) ptgs[0];
  801. Object[][] values = aptg.getTokenArrayValues();
  802. assertEquals(ErrorConstant.valueOf(FormulaError.REF.getCode()), values[0][3]);
  803. assertEquals(Boolean.FALSE, values[1][0]);
  804. }
  805. @Test
  806. void testParseStringElementInArray() {
  807. Ptg[] ptgs;
  808. ptgs = parseFormula("MAX({\"5\"},3)");
  809. confirmTokenClasses(ptgs, ArrayPtg.class, IntPtg.class, FuncVarPtg.class);
  810. Object element = ((ArrayPtg)ptgs[0]).getTokenArrayValues()[0][0];
  811. // this would cause ClassCastException below
  812. assertFalse(element instanceof UnicodeString, "Wrong encoding of array element value");
  813. assertSame(String.class, element.getClass());
  814. // make sure the formula encodes OK
  815. int encSize = Ptg.getEncodedSize(ptgs);
  816. byte[] data = new byte[encSize];
  817. Ptg.serializePtgs(ptgs, data, 0);
  818. byte[] expData = HexRead.readFromString(
  819. "20 00 00 00 00 00 00 00 " // tArray
  820. + "1E 03 00 " // tInt(3)
  821. + "42 02 07 00 " // tFuncVar(MAX) 2-arg
  822. + "00 00 00 " // Array data: 1 col, 1 row
  823. + "02 01 00 00 35" // elem (type=string, len=1, "5")
  824. );
  825. assertArrayEquals(expData, data);
  826. int initSize = Ptg.getEncodedSizeWithoutArrayData(ptgs);
  827. Ptg[] ptgs2 = Ptg.readTokens(initSize, new LittleEndianByteArrayInputStream(data));
  828. confirmTokenClasses(ptgs2, ArrayPtg.class, IntPtg.class, FuncVarPtg.class);
  829. }
  830. @Test
  831. void testParseArrayNegativeElement() {
  832. Ptg[] ptgs;
  833. try {
  834. ptgs = parseFormula("{-42}");
  835. } catch (FormulaParseException e) {
  836. if (e.getMessage().equals("Parse error near char 1 '-' in specified formula '{-42}'. Expected Integer")) {
  837. fail("Identified bug - failed to parse negative array element.");
  838. }
  839. throw e;
  840. }
  841. confirmTokenClasses(ptgs, ArrayPtg.class);
  842. Object element = ((ArrayPtg)ptgs[0]).getTokenArrayValues()[0][0];
  843. assertEquals(-42.0, (Double) element, 0.0);
  844. // Should be able to handle whitespace between unary minus and digits (Excel
  845. // accepts this formula after presenting the user with a confirmation dialog).
  846. ptgs = parseFormula("{- 5}");
  847. element = ((ArrayPtg)ptgs[0]).getTokenArrayValues()[0][0];
  848. assertEquals(-5.0, (Double) element, 0.0);
  849. }
  850. @Test
  851. void testRangeOperator() throws IOException {
  852. HSSFWorkbook wb = new HSSFWorkbook();
  853. HSSFSheet sheet = wb.createSheet();
  854. HSSFCell cell = sheet.createRow(0).createCell(0);
  855. wb.setSheetName(0, "Sheet1");
  856. cell.setCellFormula("Sheet1!B$4:Sheet1!$C1"); // explicit range ':' operator
  857. assertEquals("Sheet1!B$4:Sheet1!$C1", cell.getCellFormula());
  858. cell.setCellFormula("Sheet1!B$4:$C1"); // plain area ref
  859. assertEquals("Sheet1!B1:$C$4", cell.getCellFormula()); // note - area ref is normalised
  860. cell.setCellFormula("Sheet1!$C1...B$4"); // different syntax for plain area ref
  861. assertEquals("Sheet1!B1:$C$4", cell.getCellFormula());
  862. // with funny sheet name
  863. wb.setSheetName(0, "A1...A2");
  864. cell.setCellFormula("A1...A2!B1");
  865. assertEquals("A1...A2!B1", cell.getCellFormula());
  866. wb.close();
  867. }
  868. @Test
  869. void testBooleanNamedSheet() throws IOException {
  870. HSSFWorkbook wb = new HSSFWorkbook();
  871. HSSFSheet sheet = wb.createSheet("true");
  872. HSSFCell cell = sheet.createRow(0).createCell(0);
  873. cell.setCellFormula("'true'!B2");
  874. assertEquals("'true'!B2", cell.getCellFormula());
  875. wb.close();
  876. }
  877. @Test
  878. void testParseExternalWorkbookReference() throws IOException {
  879. HSSFWorkbook wbA = HSSFTestDataSamples.openSampleWorkbook("multibookFormulaA.xls");
  880. HSSFCell cell = wbA.getSheetAt(0).getRow(0).getCell(0);
  881. // make sure formula in sample is as expected
  882. assertEquals("[multibookFormulaB.xls]BSheet1!B1", cell.getCellFormula());
  883. Ptg[] expectedPtgs = FormulaExtractor.getPtgs(cell);
  884. confirmSingle3DRef(expectedPtgs, 1);
  885. // now try (re-)parsing the formula
  886. Ptg[] actualPtgs = parse("[multibookFormulaB.xls]BSheet1!B1", wbA);
  887. confirmSingle3DRef(actualPtgs, 1); // externalSheetIndex 1 -> BSheet1
  888. // try parsing a formula pointing to a different external sheet
  889. Ptg[] otherPtgs = parse("[multibookFormulaB.xls]AnotherSheet!B1", wbA);
  890. confirmSingle3DRef(otherPtgs, 0); // externalSheetIndex 0 -> AnotherSheet
  891. // try setting the same formula in a cell
  892. cell.setCellFormula("[multibookFormulaB.xls]AnotherSheet!B1");
  893. assertEquals("[multibookFormulaB.xls]AnotherSheet!B1", cell.getCellFormula());
  894. wbA.close();
  895. }
  896. private static void confirmSingle3DRef(Ptg[] ptgs, int expectedExternSheetIndex) {
  897. assertEquals(1, ptgs.length);
  898. Ptg ptg0 = ptgs[0];
  899. assertTrue(ptg0 instanceof Ref3DPtg);
  900. assertEquals(expectedExternSheetIndex, ((Ref3DPtg)ptg0).getExternSheetIndex());
  901. }
  902. @Test
  903. void testUnion() throws IOException {
  904. String formula = "Sheet1!$B$2:$C$3,OFFSET(Sheet1!$E$2:$E$4,1,Sheet1!$A$1),Sheet1!$D$6";
  905. HSSFWorkbook wb = new HSSFWorkbook();
  906. wb.createSheet("Sheet1");
  907. Ptg[] ptgs = FormulaParser.parse(formula, HSSFEvaluationWorkbook.create(wb), FormulaType.CELL, -1);
  908. confirmTokenClasses(ptgs,
  909. // TODO - AttrPtg.class, // Excel prepends this
  910. MemFuncPtg.class,
  911. Area3DPtg.class,
  912. Area3DPtg.class,
  913. IntPtg.class,
  914. Ref3DPtg.class,
  915. FuncVarPtg.class,
  916. UnionPtg.class,
  917. Ref3DPtg.class,
  918. UnionPtg.class
  919. );
  920. MemFuncPtg mf = (MemFuncPtg)ptgs[0];
  921. assertEquals(45, mf.getLenRefSubexpression());
  922. // We don't check the type of the operands.
  923. confirmTokenClasses("1,2", MemAreaPtg.class, IntPtg.class, IntPtg.class, UnionPtg.class);
  924. wb.close();
  925. }
  926. @Test
  927. void testIntersection() throws IOException {
  928. String formula = "Sheet1!$B$2:$C$3 OFFSET(Sheet1!$E$2:$E$4, 1,Sheet1!$A$1) Sheet1!$D$6";
  929. HSSFWorkbook wb = new HSSFWorkbook();
  930. wb.createSheet("Sheet1");
  931. Ptg[] ptgs = FormulaParser.parse(formula, HSSFEvaluationWorkbook.create(wb), FormulaType.CELL, -1);
  932. confirmTokenClasses(ptgs,
  933. // TODO - AttrPtg.class, // Excel prepends this
  934. MemFuncPtg.class,
  935. Area3DPtg.class,
  936. Area3DPtg.class,
  937. IntPtg.class,
  938. Ref3DPtg.class,
  939. FuncVarPtg.class,
  940. IntersectionPtg.class,
  941. Ref3DPtg.class,
  942. IntersectionPtg.class
  943. );
  944. MemFuncPtg mf = (MemFuncPtg)ptgs[0];
  945. assertEquals(45, mf.getLenRefSubexpression());
  946. // This used to be an error but now parses. Union has the same behaviour.
  947. confirmTokenClasses("1 2", MemAreaPtg.class, IntPtg.class, IntPtg.class, IntersectionPtg.class);
  948. wb.close();
  949. }
  950. @Test
  951. void testComparisonInParen() {
  952. confirmTokenClasses("(A1 > B2)",
  953. RefPtg.class,
  954. RefPtg.class,
  955. GreaterThanPtg.class,
  956. ParenthesisPtg.class
  957. );
  958. }
  959. @Test
  960. void testUnionInParen() {
  961. confirmTokenClasses("(A1:B2,B2:C3)",
  962. MemAreaPtg.class,
  963. AreaPtg.class,
  964. AreaPtg.class,
  965. UnionPtg.class,
  966. ParenthesisPtg.class
  967. );
  968. }
  969. @Test
  970. void testIntersectionInParen() {
  971. confirmTokenClasses("(A1:B2 B2:C3)",
  972. MemAreaPtg.class,
  973. AreaPtg.class,
  974. AreaPtg.class,
  975. IntersectionPtg.class,
  976. ParenthesisPtg.class
  977. );
  978. }
  979. // https://bz.apache.org/bugzilla/show_bug.cgi?id=60980
  980. @Test
  981. void testIntersectionInFunctionArgs() {
  982. confirmTokenClasses("SUM(A1:B2 B2:C3)",
  983. MemAreaPtg.class,
  984. AreaPtg.class,
  985. AreaPtg.class,
  986. IntersectionPtg.class,
  987. AttrPtg.class
  988. );
  989. }
  990. @Test
  991. void testIntersectionNamesInFunctionArgs() {
  992. HSSFWorkbook wb = new HSSFWorkbook();
  993. HSSFName name1 = wb.createName();
  994. name1.setNameName("foo1");
  995. name1.setRefersToFormula("A1:A3");
  996. HSSFName name2 = wb.createName();
  997. name2.setNameName("foo2");
  998. name2.setRefersToFormula("A1:B3");
  999. Ptg[] ptgs = FormulaParser.parse("SUM(foo1 foo2)", HSSFEvaluationWorkbook.create(wb), FormulaType.CELL, -1);
  1000. confirmTokenClasses(ptgs,
  1001. MemFuncPtg.class,
  1002. NamePtg.class,
  1003. NamePtg.class,
  1004. IntersectionPtg.class,
  1005. AttrPtg.class
  1006. );
  1007. }
  1008. @Test
  1009. void testRange_bug46643() throws IOException {
  1010. String formula = "Sheet1!A1:Sheet1!B3";
  1011. HSSFWorkbook wb = new HSSFWorkbook();
  1012. wb.createSheet("Sheet1");
  1013. Ptg[] ptgs = FormulaParser.parse(formula, HSSFEvaluationWorkbook.create(wb), FormulaType.CELL, -1, -1);
  1014. if (ptgs.length == 3) {
  1015. confirmTokenClasses(ptgs, Ref3DPtg.class, Ref3DPtg.class, RangePtg.class);
  1016. fail("Identified bug 46643");
  1017. }
  1018. confirmTokenClasses(ptgs,
  1019. MemFuncPtg.class,
  1020. Ref3DPtg.class,
  1021. Ref3DPtg.class,
  1022. RangePtg.class
  1023. );
  1024. MemFuncPtg mf = (MemFuncPtg)ptgs[0];
  1025. assertEquals(15, mf.getLenRefSubexpression());
  1026. wb.close();
  1027. }
  1028. /** Named ranges with backslashes, e.g. 'POI\\2009' */
  1029. @Test
  1030. void testBackSlashInNames() throws IOException {
  1031. HSSFWorkbook wb = new HSSFWorkbook();
  1032. HSSFName name = wb.createName();
  1033. name.setNameName("POI\\2009");
  1034. name.setRefersToFormula("Sheet1!$A$1");
  1035. HSSFSheet sheet = wb.createSheet();
  1036. HSSFRow row = sheet.createRow(0);
  1037. HSSFCell cell_C1 = row.createCell(2);
  1038. cell_C1.setCellFormula("POI\\2009");
  1039. assertEquals("POI\\2009", cell_C1.getCellFormula());
  1040. HSSFCell cell_D1 = row.createCell(2);
  1041. cell_D1.setCellFormula("NOT(POI\\2009=\"3.5-final\")");
  1042. assertEquals("NOT(POI\\2009=\"3.5-final\")", cell_D1.getCellFormula());
  1043. wb.close();
  1044. }
  1045. /**
  1046. * See the related/similar test: {@link BaseTestBugzillaIssues#bug42448()}
  1047. */
  1048. @Test
  1049. void testParseAbnormalSheetNamesAndRanges_bug42448() throws IOException {
  1050. try (HSSFWorkbook wb = new HSSFWorkbook()) {
  1051. wb.createSheet("A");
  1052. assertDoesNotThrow(() -> parse("SUM(A!C7:A!C67)", wb), "Identified bug 42448");
  1053. // the exact example from the bugzilla description:
  1054. parse("SUMPRODUCT(A!C7:A!C67, B8:B68) / B69", wb);
  1055. }
  1056. }
  1057. @Test
  1058. void testRangeFuncOperand_bug46951() throws IOException {
  1059. try (HSSFWorkbook wb = new HSSFWorkbook()) {
  1060. Ptg[] ptgs;
  1061. try {
  1062. ptgs = parse("SUM(C1:OFFSET(C1,0,B1))", wb);
  1063. } catch (RuntimeException e) {
  1064. if (e.getMessage().equals("Specified named range 'OFFSET' does not exist in the current workbook.")) {
  1065. fail("Identified bug 46951");
  1066. }
  1067. throw e;
  1068. }
  1069. confirmTokenClasses(ptgs,
  1070. MemFuncPtg.class, // [len=23]
  1071. RefPtg.class, // [C1]
  1072. RefPtg.class, // [C1]
  1073. IntPtg.class, // [0]
  1074. RefPtg.class, // [B1]
  1075. FuncVarPtg.class, // [OFFSET nArgs=3]
  1076. RangePtg.class, //
  1077. AttrPtg.class // [sum ]
  1078. );
  1079. }
  1080. }
  1081. @Test
  1082. void testUnionOfFullCollFullRowRef() throws IOException {
  1083. parseFormula("3:4");
  1084. Ptg[] ptgs = parseFormula("$Z:$AC");
  1085. confirmTokenClasses(ptgs, AreaPtg.class);
  1086. parseFormula("B:B");
  1087. ptgs = parseFormula("$11:$13");
  1088. confirmTokenClasses(ptgs, AreaPtg.class);
  1089. ptgs = parseFormula("$A:$A,$1:$4");
  1090. confirmTokenClasses(ptgs, MemAreaPtg.class,
  1091. AreaPtg.class,
  1092. AreaPtg.class,
  1093. UnionPtg.class
  1094. );
  1095. HSSFWorkbook wb = new HSSFWorkbook();
  1096. wb.createSheet("Sheet1");
  1097. ptgs = parse("Sheet1!$A:$A,Sheet1!$1:$4", wb);
  1098. confirmTokenClasses(ptgs, MemFuncPtg.class,
  1099. Area3DPtg.class,
  1100. Area3DPtg.class,
  1101. UnionPtg.class
  1102. );
  1103. ptgs = parse("'Sheet1'!$A:$A,'Sheet1'!$1:$4", wb);
  1104. confirmTokenClasses(ptgs,
  1105. MemFuncPtg.class,
  1106. Area3DPtg.class,
  1107. Area3DPtg.class,
  1108. UnionPtg.class
  1109. );
  1110. wb.close();
  1111. }
  1112. @Test
  1113. void testExplicitRangeWithTwoSheetNames() throws IOException {
  1114. HSSFWorkbook wb = new HSSFWorkbook();
  1115. wb.createSheet("Sheet1");
  1116. Ptg[] ptgs = parse("Sheet1!F1:Sheet1!G2", wb);
  1117. confirmTokenClasses(ptgs,
  1118. MemFuncPtg.class,
  1119. Ref3DPtg.class,
  1120. Ref3DPtg.class,
  1121. RangePtg.class
  1122. );
  1123. MemFuncPtg mf;
  1124. mf = (MemFuncPtg)ptgs[0];
  1125. assertEquals(15, mf.getLenRefSubexpression());
  1126. wb.close();
  1127. }
  1128. /**
  1129. * Checks that the area-ref and explicit range operators get the right associativity
  1130. * and that the {@link MemFuncPtg} / {@link MemAreaPtg} is added correctly
  1131. */
  1132. @Test
  1133. void testComplexExplicitRangeEncodings() {
  1134. Ptg[] ptgs;
  1135. ptgs = parseFormula("SUM(OFFSET(A1,0,0):B2:C3:D4:E5:OFFSET(F6,1,1):G7)");
  1136. confirmTokenClasses(ptgs,
  1137. // AttrPtg.class, // [volatile ] // POI doesn't do this yet (Apr 2009)
  1138. MemFuncPtg.class, // len 57
  1139. RefPtg.class, // [A1]
  1140. IntPtg.class, // [0]
  1141. IntPtg.class, // [0]
  1142. FuncVarPtg.class, // [OFFSET nArgs=3]
  1143. AreaPtg.class, // [B2:C3]
  1144. RangePtg.class,
  1145. AreaPtg.class, // [D4:E5]
  1146. RangePtg.class,
  1147. RefPtg.class, // [F6]
  1148. IntPtg.class, // [1]
  1149. IntPtg.class, // [1]
  1150. FuncVarPtg.class, // [OFFSET nArgs=3]
  1151. RangePtg.class,
  1152. RefPtg.class, // [G7]
  1153. RangePtg.class,
  1154. AttrPtg.class // [sum ]
  1155. );
  1156. MemFuncPtg mf = (MemFuncPtg)ptgs[0];
  1157. assertEquals(57, mf.getLenRefSubexpression());
  1158. assertEquals("D4:E5", ptgs[7].toFormulaString());
  1159. assertTrue(((AttrPtg)ptgs[16]).isSum());
  1160. ptgs = parseFormula("SUM(A1:B2:C3:D4)");
  1161. confirmTokenClasses(ptgs,
  1162. // AttrPtg.class, // [volatile ] // POI doesn't do this yet (Apr 2009)
  1163. MemAreaPtg.class, // len 19
  1164. AreaPtg.class, // [A1:B2]
  1165. AreaPtg.class, // [C3:D4]
  1166. RangePtg.class,
  1167. AttrPtg.class // [sum ]
  1168. );
  1169. MemAreaPtg ma = (MemAreaPtg)ptgs[0];
  1170. assertEquals(19, ma.getLenRefSubexpression());
  1171. }
  1172. /**
  1173. * Mostly confirming that erroneous conditions are detected. Actual error message wording is not critical.
  1174. *
  1175. */
  1176. @Test
  1177. void testEdgeCaseParserErrors() throws IOException {
  1178. HSSFWorkbook wb = new HSSFWorkbook();
  1179. wb.createSheet("Sheet1");
  1180. //confirmParseError(wb, "A1:ROUND(B1,1)", "The RHS of the range operator ':' at position 3 is not a proper reference.");
  1181. confirmParseError(wb, "Sheet1!!!", "Parse error near char 7 '!' in specified formula 'Sheet1!!!'. Expected number, string, defined name, or data table");
  1182. confirmParseError(wb, "Sheet1!.Name", "Parse error near char 7 '.' in specified formula 'Sheet1!.Name'. Expected number, string, defined name, or data table");
  1183. confirmParseError(wb, "Sheet1!Sheet1", "Specified name 'Sheet1' for sheet Sheet1 not found");
  1184. confirmParseError(wb, "Sheet1!F:Sheet1!G", "'Sheet1!F' is not a proper reference.");
  1185. confirmParseError(wb, "Sheet1!F..foobar", "Complete area reference expected after sheet name at index 11.");
  1186. confirmParseError(wb, "Sheet1!A .. B", "Dotted range (full row or column) expression 'A .. B' must not contain whitespace.");
  1187. confirmParseError(wb, "Sheet1!A...B", "Dotted range (full row or column) expression 'A...B' must have exactly 2 dots.");
  1188. confirmParseError(wb, "Sheet1!A foobar", "Second part of cell reference expected after sheet name at index 10.");
  1189. confirmParseError(wb, "foobar", "Specified named range 'foobar' does not exist in the current workbook.");
  1190. confirmParseError(wb, "A1:1", "The RHS of the range operator ':' at position 3 is not a proper reference.");
  1191. wb.close();
  1192. }
  1193. private static void confirmParseError(HSSFWorkbook wb, String formula, String expectedMessage) {
  1194. FormulaParseException e = assertThrows(FormulaParseException.class, () -> parse(formula, wb));
  1195. confirmParseException(e, expectedMessage);
  1196. }
  1197. /**
  1198. * In bug 47078, POI had trouble evaluating a defined name flagged as 'complex'.
  1199. * POI should also be able to parse such defined names.
  1200. */
  1201. @Test
  1202. void testParseComplexName() throws IOException {
  1203. // Mock up a spreadsheet to match the critical details of the sample
  1204. try (HSSFWorkbook wb = new HSSFWorkbook()) {
  1205. wb.createSheet("Sheet1");
  1206. HSSFName definedName = wb.createName();
  1207. definedName.setNameName("foo");
  1208. definedName.setRefersToFormula("Sheet1!B2");
  1209. // Set the complex flag - POI doesn't usually manipulate this flag
  1210. NameRecord nameRec = TestHSSFName.getNameRecord(definedName);
  1211. nameRec.setOptionFlag((short) 0x10); // 0x10 -> complex
  1212. Ptg[] result;
  1213. try {
  1214. result = parse("1+foo", wb);
  1215. } catch (FormulaParseException e) {
  1216. if (e.getMessage().equals("Specified name 'foo' is not a range as expected.")) {
  1217. fail("Identified bug 47078c");
  1218. }
  1219. throw e;
  1220. }
  1221. confirmTokenClasses(result, IntPtg.class, NamePtg.class, AddPtg.class);
  1222. }
  1223. }
  1224. /**
  1225. * Zero is not a valid row number so cell references like 'A0' are not valid.
  1226. * Actually, they should be treated like defined names.
  1227. * <br>
  1228. * In addition, leading zeros (on the row component) should be removed from cell
  1229. * references during parsing.
  1230. */
  1231. @Test
  1232. void testZeroRowRefs() throws IOException {
  1233. String badCellRef = "B0"; // bad because zero is not a valid row number
  1234. String leadingZeroCellRef = "B000001"; // this should get parsed as "B1"
  1235. HSSFWorkbook wb = new HSSFWorkbook();
  1236. FormulaParseException e = assertThrows(FormulaParseException.class, () -> parse(badCellRef, wb),
  1237. "Identified bug 47312b - Shouldn't be able to parse cell ref '" + badCellRef + "'.");
  1238. confirmParseException(e, "Specified named range '" + badCellRef + "' does not exist in the current workbook.");
  1239. Ptg[] ptgs;
  1240. try {
  1241. ptgs = parse(leadingZeroCellRef, wb);
  1242. assertEquals("B1", ptgs[0].toFormulaString());
  1243. } catch (FormulaParseException e2) {
  1244. confirmParseException(e2, "Specified named range '" + leadingZeroCellRef + "' does not exist in the current workbook.");
  1245. // close but no cigar
  1246. fail("Identified bug 47312c - '" + leadingZeroCellRef + "' should parse as 'B1'.");
  1247. }
  1248. // create a defined name called 'B0' and try again
  1249. Name n = wb.createName();
  1250. n.setNameName("B0");
  1251. n.setRefersToFormula("1+1");
  1252. ptgs = parse("B0", wb);
  1253. confirmTokenClasses(ptgs, NamePtg.class);
  1254. wb.close();
  1255. }
  1256. private static void confirmParseException(FormulaParseException e, String expMsg) {
  1257. assertEquals(expMsg, e.getMessage());
  1258. }
  1259. @Test
  1260. void test57196_Formula() throws IOException {
  1261. HSSFWorkbook wb = new HSSFWorkbook();
  1262. Ptg[] ptgs = parse("DEC2HEX(HEX2DEC(O8)-O2+D2)", wb, FormulaType.CELL, -1);
  1263. assertNotNull(ptgs, "Ptg array should not be null");
  1264. confirmTokenClasses(ptgs,
  1265. NameXPtg.class, // ??
  1266. NameXPtg.class, // ??
  1267. RefPtg.class, // O8
  1268. FuncVarPtg.class, // HEX2DEC
  1269. RefPtg.class, // O2
  1270. SubtractPtg.class,
  1271. RefPtg.class, // D2
  1272. AddPtg.class,
  1273. FuncVarPtg.class // DEC2HEX
  1274. );
  1275. RefPtg o8 = (RefPtg) ptgs[2];
  1276. FuncVarPtg hex2Dec = (FuncVarPtg) ptgs[3];
  1277. RefPtg o2 = (RefPtg) ptgs[4];
  1278. RefPtg d2 = (RefPtg) ptgs[6];
  1279. FuncVarPtg dec2Hex = (FuncVarPtg) ptgs[8];
  1280. assertEquals("O8", o8.toFormulaString());
  1281. assertEquals(255, hex2Dec.getFunctionIndex());
  1282. //assertEquals("", hex2Dec.toString());
  1283. assertEquals("O2", o2.toFormulaString());
  1284. assertEquals("D2", d2.toFormulaString());
  1285. assertEquals(255, dec2Hex.getFunctionIndex());
  1286. wb.close();
  1287. }
  1288. }