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

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