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.

TestXSSFBugs.java 103KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.xssf.usermodel;
  16. import static org.junit.Assert.assertArrayEquals;
  17. import static org.junit.Assert.assertEquals;
  18. import static org.junit.Assert.assertFalse;
  19. import static org.junit.Assert.assertNotNull;
  20. import static org.junit.Assert.assertNull;
  21. import static org.junit.Assert.assertTrue;
  22. import static org.junit.Assert.fail;
  23. import java.io.ByteArrayInputStream;
  24. import java.io.ByteArrayOutputStream;
  25. import java.io.File;
  26. import java.io.FileInputStream;
  27. import java.io.FileOutputStream;
  28. import java.io.IOException;
  29. import java.io.InputStream;
  30. import java.io.OutputStream;
  31. import java.util.Arrays;
  32. import java.util.Calendar;
  33. import java.util.List;
  34. import java.util.Map;
  35. import java.util.Set;
  36. import java.util.TimeZone;
  37. import java.util.TreeMap;
  38. import org.apache.poi.EncryptedDocumentException;
  39. import org.apache.poi.POIDataSamples;
  40. import org.apache.poi.POIXMLDocumentPart;
  41. import org.apache.poi.POIXMLException;
  42. import org.apache.poi.POIXMLProperties;
  43. import org.apache.poi.hssf.HSSFTestDataSamples;
  44. import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
  45. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  46. import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
  47. import org.apache.poi.openxml4j.opc.OPCPackage;
  48. import org.apache.poi.openxml4j.opc.PackageAccess;
  49. import org.apache.poi.openxml4j.opc.PackagePart;
  50. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  51. import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
  52. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  53. import org.apache.poi.ss.formula.WorkbookEvaluator;
  54. import org.apache.poi.ss.formula.eval.ErrorEval;
  55. import org.apache.poi.ss.formula.eval.NumberEval;
  56. import org.apache.poi.ss.formula.eval.ValueEval;
  57. import org.apache.poi.ss.formula.functions.Function;
  58. import org.apache.poi.ss.usermodel.BaseTestBugzillaIssues;
  59. import org.apache.poi.ss.usermodel.Cell;
  60. import org.apache.poi.ss.usermodel.CellStyle;
  61. import org.apache.poi.ss.usermodel.CellValue;
  62. import org.apache.poi.ss.usermodel.ClientAnchor;
  63. import org.apache.poi.ss.usermodel.Comment;
  64. import org.apache.poi.ss.usermodel.CreationHelper;
  65. import org.apache.poi.ss.usermodel.DataFormat;
  66. import org.apache.poi.ss.usermodel.DataFormatter;
  67. import org.apache.poi.ss.usermodel.DateUtil;
  68. import org.apache.poi.ss.usermodel.Drawing;
  69. import org.apache.poi.ss.usermodel.Font;
  70. import org.apache.poi.ss.usermodel.FormulaError;
  71. import org.apache.poi.ss.usermodel.FormulaEvaluator;
  72. import org.apache.poi.ss.usermodel.Hyperlink;
  73. import org.apache.poi.ss.usermodel.IndexedColors;
  74. import org.apache.poi.ss.usermodel.Name;
  75. import org.apache.poi.ss.usermodel.PrintSetup;
  76. import org.apache.poi.ss.usermodel.Row;
  77. import org.apache.poi.ss.usermodel.Sheet;
  78. import org.apache.poi.ss.usermodel.SheetConditionalFormatting;
  79. import org.apache.poi.ss.usermodel.Workbook;
  80. import org.apache.poi.ss.usermodel.WorkbookFactory;
  81. import org.apache.poi.ss.util.AreaReference;
  82. import org.apache.poi.ss.util.CellRangeAddress;
  83. import org.apache.poi.ss.util.CellReference;
  84. import org.apache.poi.util.LocaleUtil;
  85. import org.apache.poi.util.TempFile;
  86. import org.apache.poi.xssf.XLSBUnsupportedException;
  87. import org.apache.poi.xssf.XSSFITestDataProvider;
  88. import org.apache.poi.xssf.XSSFTestDataSamples;
  89. import org.apache.poi.xssf.model.CalculationChain;
  90. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  91. import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill;
  92. import org.junit.Ignore;
  93. import org.junit.Test;
  94. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcCell;
  95. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols;
  96. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName;
  97. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedNames;
  98. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
  99. import org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTFontImpl;
  100. public final class TestXSSFBugs extends BaseTestBugzillaIssues {
  101. public TestXSSFBugs() {
  102. super(XSSFITestDataProvider.instance);
  103. }
  104. /**
  105. * test writing a file with large number of unique strings,
  106. * open resulting file in Excel to check results!
  107. */
  108. @Test
  109. public void bug15375_2() {
  110. bug15375(1000);
  111. }
  112. /**
  113. * Named ranges had the right reference, but
  114. * the wrong sheet name
  115. */
  116. @Test
  117. public void bug45430() throws Exception {
  118. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("45430.xlsx");
  119. assertFalse(wb.isMacroEnabled());
  120. assertEquals(3, wb.getNumberOfNames());
  121. assertEquals(0, wb.getNameAt(0).getCTName().getLocalSheetId());
  122. assertFalse(wb.getNameAt(0).getCTName().isSetLocalSheetId());
  123. assertEquals("SheetA!$A$1", wb.getNameAt(0).getRefersToFormula());
  124. assertEquals("SheetA", wb.getNameAt(0).getSheetName());
  125. assertEquals(0, wb.getNameAt(1).getCTName().getLocalSheetId());
  126. assertFalse(wb.getNameAt(1).getCTName().isSetLocalSheetId());
  127. assertEquals("SheetB!$A$1", wb.getNameAt(1).getRefersToFormula());
  128. assertEquals("SheetB", wb.getNameAt(1).getSheetName());
  129. assertEquals(0, wb.getNameAt(2).getCTName().getLocalSheetId());
  130. assertFalse(wb.getNameAt(2).getCTName().isSetLocalSheetId());
  131. assertEquals("SheetC!$A$1", wb.getNameAt(2).getRefersToFormula());
  132. assertEquals("SheetC", wb.getNameAt(2).getSheetName());
  133. // Save and re-load, still there
  134. XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  135. assertEquals(3, nwb.getNumberOfNames());
  136. assertEquals("SheetA!$A$1", nwb.getNameAt(0).getRefersToFormula());
  137. nwb.close();
  138. wb.close();
  139. }
  140. /**
  141. * We should carry vba macros over after save
  142. */
  143. @Test
  144. public void bug45431() throws Exception {
  145. XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("45431.xlsm");
  146. OPCPackage pkg1 = wb1.getPackage();
  147. assertTrue(wb1.isMacroEnabled());
  148. // Check the various macro related bits can be found
  149. PackagePart vba = pkg1.getPart(
  150. PackagingURIHelper.createPartName("/xl/vbaProject.bin")
  151. );
  152. assertNotNull(vba);
  153. // And the drawing bit
  154. PackagePart drw = pkg1.getPart(
  155. PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
  156. );
  157. assertNotNull(drw);
  158. // Save and re-open, both still there
  159. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  160. pkg1.close();
  161. wb1.close();
  162. OPCPackage pkg2 = wb2.getPackage();
  163. assertTrue(wb2.isMacroEnabled());
  164. vba = pkg2.getPart(
  165. PackagingURIHelper.createPartName("/xl/vbaProject.bin")
  166. );
  167. assertNotNull(vba);
  168. drw = pkg2.getPart(
  169. PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
  170. );
  171. assertNotNull(drw);
  172. // And again, just to be sure
  173. XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
  174. pkg2.close();
  175. wb2.close();
  176. OPCPackage pkg3 = wb3.getPackage();
  177. assertTrue(wb3.isMacroEnabled());
  178. vba = pkg3.getPart(
  179. PackagingURIHelper.createPartName("/xl/vbaProject.bin")
  180. );
  181. assertNotNull(vba);
  182. drw = pkg3.getPart(
  183. PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
  184. );
  185. assertNotNull(drw);
  186. pkg3.close();
  187. wb3.close();
  188. }
  189. @Test
  190. public void bug47504() throws Exception {
  191. XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47504.xlsx");
  192. assertEquals(1, wb1.getNumberOfSheets());
  193. XSSFSheet sh = wb1.getSheetAt(0);
  194. XSSFDrawing drawing = sh.createDrawingPatriarch();
  195. List<POIXMLDocumentPart> rels = drawing.getRelations();
  196. assertEquals(1, rels.size());
  197. assertEquals("Sheet1!A1", rels.get(0).getPackageRelationship().getTargetURI().getFragment());
  198. // And again, just to be sure
  199. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  200. wb1.close();
  201. assertEquals(1, wb2.getNumberOfSheets());
  202. sh = wb2.getSheetAt(0);
  203. drawing = sh.createDrawingPatriarch();
  204. rels = drawing.getRelations();
  205. assertEquals(1, rels.size());
  206. assertEquals("Sheet1!A1", rels.get(0).getPackageRelationship().getTargetURI().getFragment());
  207. wb2.close();
  208. }
  209. /**
  210. * Excel will sometimes write a button with a textbox
  211. * containing &gt;br&lt; (not closed!).
  212. * Clearly Excel shouldn't do this, but test that we can
  213. * read the file despite the naughtyness
  214. */
  215. @Test
  216. public void bug49020() throws Exception {
  217. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("BrNotClosed.xlsx");
  218. wb.close();
  219. }
  220. /**
  221. * ensure that CTPhoneticPr is loaded by the ooxml test suite so that it is included in poi-ooxml-schemas
  222. */
  223. @Test
  224. public void bug49325() throws Exception {
  225. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49325.xlsx");
  226. CTWorksheet sh = wb.getSheetAt(0).getCTWorksheet();
  227. assertNotNull(sh.getPhoneticPr());
  228. wb.close();
  229. }
  230. /**
  231. * Names which are defined with a Sheet
  232. * should return that sheet index properly
  233. */
  234. @Test
  235. public void bug48923() throws Exception {
  236. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48923.xlsx");
  237. assertEquals(4, wb.getNumberOfNames());
  238. Name b1 = wb.getName("NameB1");
  239. Name b2 = wb.getName("NameB2");
  240. Name sheet2 = wb.getName("NameSheet2");
  241. Name test = wb.getName("Test");
  242. assertNotNull(b1);
  243. assertEquals("NameB1", b1.getNameName());
  244. assertEquals("Sheet1", b1.getSheetName());
  245. assertEquals(-1, b1.getSheetIndex());
  246. assertNotNull(b2);
  247. assertEquals("NameB2", b2.getNameName());
  248. assertEquals("Sheet1", b2.getSheetName());
  249. assertEquals(-1, b2.getSheetIndex());
  250. assertNotNull(sheet2);
  251. assertEquals("NameSheet2", sheet2.getNameName());
  252. assertEquals("Sheet2", sheet2.getSheetName());
  253. assertEquals(-1, sheet2.getSheetIndex());
  254. assertNotNull(test);
  255. assertEquals("Test", test.getNameName());
  256. assertEquals("Sheet1", test.getSheetName());
  257. assertEquals(-1, test.getSheetIndex());
  258. wb.close();
  259. }
  260. /**
  261. * Problem with evaluation formulas due to
  262. * NameXPtgs.
  263. * Blows up on:
  264. * IF(B6= (ROUNDUP(B6,0) + ROUNDDOWN(B6,0))/2, MROUND(B6,2),ROUND(B6,0))
  265. *
  266. * TODO: delete this test case when MROUND and VAR are implemented
  267. */
  268. @Test
  269. public void bug48539() throws Exception {
  270. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48539.xlsx");
  271. try {
  272. assertEquals(3, wb.getNumberOfSheets());
  273. assertEquals(0, wb.getNumberOfNames());
  274. // Try each cell individually
  275. XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb);
  276. for(int i=0; i<wb.getNumberOfSheets(); i++) {
  277. Sheet s = wb.getSheetAt(i);
  278. for(Row r : s) {
  279. for(Cell c : r) {
  280. if(c.getCellType() == Cell.CELL_TYPE_FORMULA) {
  281. String formula = c.getCellFormula();
  282. CellValue cv;
  283. try {
  284. cv = eval.evaluate(c);
  285. } catch (Exception e) {
  286. throw new RuntimeException("Can't evaluate formula: " + formula, e);
  287. }
  288. if(cv.getCellType() == Cell.CELL_TYPE_NUMERIC) {
  289. // assert that the calculated value agrees with
  290. // the cached formula result calculated by Excel
  291. double cachedFormulaResult = c.getNumericCellValue();
  292. double evaluatedFormulaResult = cv.getNumberValue();
  293. assertEquals(c.getCellFormula(), cachedFormulaResult, evaluatedFormulaResult, 1E-7);
  294. }
  295. }
  296. }
  297. }
  298. }
  299. // Now all of them
  300. XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
  301. } finally {
  302. wb.close();
  303. }
  304. }
  305. /**
  306. * Foreground colours should be found even if
  307. * a theme is used
  308. */
  309. @Test
  310. public void bug48779() throws Exception {
  311. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx");
  312. XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0);
  313. XSSFCellStyle cs = cell.getCellStyle();
  314. assertNotNull(cs);
  315. assertEquals(1, cs.getIndex());
  316. // Look at the low level xml elements
  317. assertEquals(2, cs.getCoreXf().getFillId());
  318. assertEquals(0, cs.getCoreXf().getXfId());
  319. assertEquals(true, cs.getCoreXf().getApplyFill());
  320. XSSFCellFill fg = wb.getStylesSource().getFillAt(2);
  321. assertEquals(0, fg.getFillForegroundColor().getIndexed());
  322. assertEquals(0.0, fg.getFillForegroundColor().getTint(), 0);
  323. assertEquals("FFFF0000", fg.getFillForegroundColor().getARGBHex());
  324. assertEquals(64, fg.getFillBackgroundColor().getIndexed());
  325. // Now look higher up
  326. assertNotNull(cs.getFillForegroundXSSFColor());
  327. assertEquals(0, cs.getFillForegroundColor());
  328. assertEquals("FFFF0000", cs.getFillForegroundXSSFColor().getARGBHex());
  329. assertEquals("FFFF0000", cs.getFillForegroundColorColor().getARGBHex());
  330. assertNotNull(cs.getFillBackgroundColor());
  331. assertEquals(64, cs.getFillBackgroundColor());
  332. assertEquals(null, cs.getFillBackgroundXSSFColor().getARGBHex());
  333. assertEquals(null, cs.getFillBackgroundColorColor().getARGBHex());
  334. wb.close();
  335. }
  336. /**
  337. * Ensure General and @ format are working properly
  338. * for integers
  339. */
  340. @Test
  341. public void bug47490() throws Exception {
  342. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("GeneralFormatTests.xlsx");
  343. Sheet s = wb.getSheetAt(1);
  344. Row r;
  345. DataFormatter df = new DataFormatter();
  346. r = s.getRow(1);
  347. assertEquals(1.0, r.getCell(2).getNumericCellValue(), 0);
  348. assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString());
  349. assertEquals("1", df.formatCellValue(r.getCell(2)));
  350. assertEquals("1", df.formatRawCellContents(1.0, -1, "@"));
  351. assertEquals("1", df.formatRawCellContents(1.0, -1, "General"));
  352. r = s.getRow(2);
  353. assertEquals(12.0, r.getCell(2).getNumericCellValue(), 0);
  354. assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString());
  355. assertEquals("12", df.formatCellValue(r.getCell(2)));
  356. assertEquals("12", df.formatRawCellContents(12.0, -1, "@"));
  357. assertEquals("12", df.formatRawCellContents(12.0, -1, "General"));
  358. r = s.getRow(3);
  359. assertEquals(123.0, r.getCell(2).getNumericCellValue(), 0);
  360. assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString());
  361. assertEquals("123", df.formatCellValue(r.getCell(2)));
  362. assertEquals("123", df.formatRawCellContents(123.0, -1, "@"));
  363. assertEquals("123", df.formatRawCellContents(123.0, -1, "General"));
  364. wb.close();
  365. }
  366. /**
  367. * A problem file from a non-standard source (a scientific instrument that saves its
  368. * output as an .xlsx file) that have two issues:
  369. * 1. The Content Type part name is lower-case: [content_types].xml
  370. * 2. The file appears to use backslashes as path separators
  371. *
  372. * The OPC spec tolerates both of these peculiarities, so does POI
  373. */
  374. @Test
  375. public void bug49609() throws Exception {
  376. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49609.xlsx");
  377. assertEquals("FAM", wb.getSheetName(0));
  378. assertEquals("Cycle", wb.getSheetAt(0).getRow(0).getCell(1).getStringCellValue());
  379. wb.close();
  380. }
  381. @Test
  382. public void bug49783() throws Exception {
  383. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49783.xlsx");
  384. Sheet sheet = wb.getSheetAt(0);
  385. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  386. Cell cell;
  387. cell = sheet.getRow(0).getCell(0);
  388. assertEquals("#REF!*#REF!", cell.getCellFormula());
  389. assertEquals(Cell.CELL_TYPE_ERROR, evaluator.evaluateInCell(cell).getCellType());
  390. assertEquals("#REF!", FormulaError.forInt(cell.getErrorCellValue()).getString());
  391. Name nm1 = wb.getName("sale_1");
  392. assertNotNull("name sale_1 should be present", nm1);
  393. assertEquals("Sheet1!#REF!", nm1.getRefersToFormula());
  394. Name nm2 = wb.getName("sale_2");
  395. assertNotNull("name sale_2 should be present", nm2);
  396. assertEquals("Sheet1!#REF!", nm2.getRefersToFormula());
  397. cell = sheet.getRow(1).getCell(0);
  398. assertEquals("sale_1*sale_2", cell.getCellFormula());
  399. assertEquals(Cell.CELL_TYPE_ERROR, evaluator.evaluateInCell(cell).getCellType());
  400. assertEquals("#REF!", FormulaError.forInt(cell.getErrorCellValue()).getString());
  401. wb.close();
  402. }
  403. /**
  404. * Creating a rich string of "hello world" and applying
  405. * a font to characters 1-5 means we have two strings,
  406. * "hello" and " world". As such, we need to apply
  407. * preserve spaces to the 2nd bit, lest we end up
  408. * with something like "helloworld" !
  409. */
  410. @Test
  411. public void bug49941() throws Exception {
  412. XSSFWorkbook wb1 = new XSSFWorkbook();
  413. XSSFSheet s = wb1.createSheet();
  414. XSSFRow r = s.createRow(0);
  415. XSSFCell c = r.createCell(0);
  416. // First without fonts
  417. c.setCellValue(
  418. new XSSFRichTextString(" with spaces ")
  419. );
  420. assertEquals(" with spaces ", c.getRichStringCellValue().toString());
  421. assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray());
  422. assertEquals(true, c.getRichStringCellValue().getCTRst().isSetT());
  423. // Should have the preserve set
  424. assertEquals(
  425. 1,
  426. c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength()
  427. );
  428. assertEquals(
  429. "preserve",
  430. c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().item(0).getNodeValue()
  431. );
  432. // Save and check
  433. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  434. wb1.close();
  435. s = wb2.getSheetAt(0);
  436. r = s.getRow(0);
  437. c = r.getCell(0);
  438. assertEquals(" with spaces ", c.getRichStringCellValue().toString());
  439. assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray());
  440. assertEquals(true, c.getRichStringCellValue().getCTRst().isSetT());
  441. // Change the string
  442. c.setCellValue(
  443. new XSSFRichTextString("hello world")
  444. );
  445. assertEquals("hello world", c.getRichStringCellValue().toString());
  446. // Won't have preserve
  447. assertEquals(
  448. 0,
  449. c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength()
  450. );
  451. // Apply a font
  452. XSSFFont f = wb2.createFont();
  453. f.setBold(true);
  454. c.getRichStringCellValue().applyFont(0, 5, f);
  455. assertEquals("hello world", c.getRichStringCellValue().toString());
  456. // Does need preserving on the 2nd part
  457. assertEquals(2, c.getRichStringCellValue().getCTRst().sizeOfRArray());
  458. assertEquals(
  459. 0,
  460. c.getRichStringCellValue().getCTRst().getRArray(0).xgetT().getDomNode().getAttributes().getLength()
  461. );
  462. assertEquals(
  463. 1,
  464. c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().getLength()
  465. );
  466. assertEquals(
  467. "preserve",
  468. c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().item(0).getNodeValue()
  469. );
  470. // Save and check
  471. XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
  472. wb2.close();
  473. s = wb3.getSheetAt(0);
  474. r = s.getRow(0);
  475. c = r.getCell(0);
  476. assertEquals("hello world", c.getRichStringCellValue().toString());
  477. wb3.close();
  478. }
  479. /**
  480. * Repeatedly writing the same file which has styles
  481. */
  482. @Test
  483. public void bug49940() throws Exception {
  484. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("styles.xlsx");
  485. assertEquals(3, wb.getNumberOfSheets());
  486. assertEquals(10, wb.getStylesSource().getNumCellStyles());
  487. ByteArrayOutputStream b1 = new ByteArrayOutputStream();
  488. ByteArrayOutputStream b2 = new ByteArrayOutputStream();
  489. ByteArrayOutputStream b3 = new ByteArrayOutputStream();
  490. wb.write(b1);
  491. wb.write(b2);
  492. wb.write(b3);
  493. for(byte[] data : new byte[][] {
  494. b1.toByteArray(), b2.toByteArray(), b3.toByteArray()
  495. }) {
  496. ByteArrayInputStream bais = new ByteArrayInputStream(data);
  497. XSSFWorkbook wb2 = new XSSFWorkbook(bais);
  498. assertEquals(3, wb2.getNumberOfSheets());
  499. assertEquals(10, wb2.getStylesSource().getNumCellStyles());
  500. wb2.close();
  501. }
  502. wb.close();
  503. }
  504. /**
  505. * Various ways of removing a cell formula should all zap the calcChain
  506. * entry.
  507. */
  508. @Test
  509. public void bug49966() throws Exception {
  510. XSSFWorkbook wb1 = XSSFTestDataSamples
  511. .openSampleWorkbook("shared_formulas.xlsx");
  512. XSSFSheet sheet = wb1.getSheetAt(0);
  513. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  514. // CalcChain has lots of entries
  515. CalculationChain cc = wb1.getCalculationChain();
  516. assertEquals("A2", cc.getCTCalcChain().getCArray(0).getR());
  517. assertEquals("A3", cc.getCTCalcChain().getCArray(1).getR());
  518. assertEquals("A4", cc.getCTCalcChain().getCArray(2).getR());
  519. assertEquals("A5", cc.getCTCalcChain().getCArray(3).getR());
  520. assertEquals("A6", cc.getCTCalcChain().getCArray(4).getR());
  521. assertEquals("A7", cc.getCTCalcChain().getCArray(5).getR());
  522. assertEquals("A8", cc.getCTCalcChain().getCArray(6).getR());
  523. assertEquals(40, cc.getCTCalcChain().sizeOfCArray());
  524. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  525. // Try various ways of changing the formulas
  526. // If it stays a formula, chain entry should remain
  527. // Otherwise should go
  528. sheet.getRow(1).getCell(0).setCellFormula("A1"); // stay
  529. sheet.getRow(2).getCell(0).setCellFormula(null); // go
  530. sheet.getRow(3).getCell(0).setCellType(Cell.CELL_TYPE_FORMULA); // stay
  531. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  532. sheet.getRow(4).getCell(0).setCellType(Cell.CELL_TYPE_STRING); // go
  533. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  534. validateCells(sheet);
  535. sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go
  536. validateCells(sheet);
  537. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  538. sheet.getRow(6).getCell(0).setCellType(Cell.CELL_TYPE_BLANK); // go
  539. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  540. sheet.getRow(7).getCell(0).setCellValue((String) null); // go
  541. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  542. // Save and check
  543. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  544. wb1.close();
  545. assertEquals(35, cc.getCTCalcChain().sizeOfCArray());
  546. cc = wb2.getCalculationChain();
  547. assertEquals("A2", cc.getCTCalcChain().getCArray(0).getR());
  548. assertEquals("A4", cc.getCTCalcChain().getCArray(1).getR());
  549. assertEquals("A9", cc.getCTCalcChain().getCArray(2).getR());
  550. wb2.close();
  551. }
  552. @Test
  553. public void bug49966Row() throws Exception {
  554. XSSFWorkbook wb = XSSFTestDataSamples
  555. .openSampleWorkbook("shared_formulas.xlsx");
  556. XSSFSheet sheet = wb.getSheetAt(0);
  557. validateCells(sheet);
  558. sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go
  559. validateCells(sheet);
  560. wb.close();
  561. }
  562. private void validateCells(XSSFSheet sheet) {
  563. for(Row row : sheet) {
  564. // trigger handling
  565. ((XSSFRow)row).onDocumentWrite();
  566. }
  567. }
  568. @Test
  569. public void bug49156() throws Exception {
  570. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49156.xlsx");
  571. FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
  572. Sheet sheet = wb.getSheetAt(0);
  573. for(Row row : sheet){
  574. for(Cell cell : row){
  575. if(cell.getCellType() == Cell.CELL_TYPE_FORMULA){
  576. formulaEvaluator.evaluateInCell(cell); // caused NPE on some cells
  577. }
  578. }
  579. }
  580. wb.close();
  581. }
  582. /**
  583. * Newlines are valid characters in a formula
  584. */
  585. @Test
  586. public void bug50440And51875() throws Exception {
  587. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("NewlineInFormulas.xlsx");
  588. Sheet s = wb.getSheetAt(0);
  589. Cell c = s.getRow(0).getCell(0);
  590. assertEquals("SUM(\n1,2\n)", c.getCellFormula());
  591. assertEquals(3.0, c.getNumericCellValue(), 0);
  592. FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
  593. formulaEvaluator.evaluateFormulaCell(c);
  594. assertEquals("SUM(\n1,2\n)", c.getCellFormula());
  595. assertEquals(3.0, c.getNumericCellValue(), 0);
  596. // For 51875
  597. Cell b3 = s.getRow(2).getCell(1);
  598. formulaEvaluator.evaluateFormulaCell(b3);
  599. assertEquals("B1+B2", b3.getCellFormula()); // The newline is lost for shared formulas
  600. assertEquals(3.0, b3.getNumericCellValue(), 0);
  601. wb.close();
  602. }
  603. /**
  604. * Moving a cell comment from one cell to another
  605. */
  606. @Test
  607. public void bug50795() throws Exception {
  608. XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("50795.xlsx");
  609. XSSFSheet sheet = wb1.getSheetAt(0);
  610. XSSFRow row = sheet.getRow(0);
  611. XSSFCell cellWith = row.getCell(0);
  612. XSSFCell cellWithoutComment = row.getCell(1);
  613. assertNotNull(cellWith.getCellComment());
  614. assertNull(cellWithoutComment.getCellComment());
  615. String exp = "\u0410\u0432\u0442\u043e\u0440:\ncomment";
  616. XSSFComment comment = cellWith.getCellComment();
  617. assertEquals(exp, comment.getString().getString());
  618. // Check we can write it out and read it back as-is
  619. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  620. wb1.close();
  621. sheet = wb2.getSheetAt(0);
  622. row = sheet.getRow(0);
  623. cellWith = row.getCell(0);
  624. cellWithoutComment = row.getCell(1);
  625. // Double check things are as expected
  626. assertNotNull(cellWith.getCellComment());
  627. assertNull(cellWithoutComment.getCellComment());
  628. comment = cellWith.getCellComment();
  629. assertEquals(exp, comment.getString().getString());
  630. // Move the comment
  631. cellWithoutComment.setCellComment(comment);
  632. // Write out and re-check
  633. XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
  634. wb2.close();
  635. sheet = wb3.getSheetAt(0);
  636. row = sheet.getRow(0);
  637. // Ensure it swapped over
  638. cellWith = row.getCell(0);
  639. cellWithoutComment = row.getCell(1);
  640. assertNull(cellWith.getCellComment());
  641. assertNotNull(cellWithoutComment.getCellComment());
  642. comment = cellWithoutComment.getCellComment();
  643. assertEquals(exp, comment.getString().getString());
  644. wb3.close();
  645. }
  646. /**
  647. * When the cell background colour is set with one of the first
  648. * two columns of the theme colour palette, the colours are
  649. * shades of white or black.
  650. * For those cases, ensure we don't break on reading the colour
  651. */
  652. @Test
  653. public void bug50299() throws Exception {
  654. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50299.xlsx");
  655. // Check all the colours
  656. for(int sn=0; sn<wb.getNumberOfSheets(); sn++) {
  657. Sheet s = wb.getSheetAt(sn);
  658. for(Row r : s) {
  659. for(Cell c : r) {
  660. CellStyle cs = c.getCellStyle();
  661. if(cs != null) {
  662. cs.getFillForegroundColor();
  663. }
  664. }
  665. }
  666. }
  667. // Check one bit in detail
  668. // Check that we get back foreground=0 for the theme colours,
  669. // and background=64 for the auto colouring
  670. Sheet s = wb.getSheetAt(0);
  671. assertEquals(0, s.getRow(0).getCell(8).getCellStyle().getFillForegroundColor());
  672. assertEquals(64, s.getRow(0).getCell(8).getCellStyle().getFillBackgroundColor());
  673. assertEquals(0, s.getRow(1).getCell(8).getCellStyle().getFillForegroundColor());
  674. assertEquals(64, s.getRow(1).getCell(8).getCellStyle().getFillBackgroundColor());
  675. wb.close();
  676. }
  677. /**
  678. * Excel .xls style indexed colours in a .xlsx file
  679. */
  680. @SuppressWarnings("deprecation")
  681. @Test
  682. public void bug50786() throws Exception {
  683. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50786-indexed_colours.xlsx");
  684. XSSFSheet s = wb.getSheetAt(0);
  685. XSSFRow r = s.getRow(2);
  686. // Check we have the right cell
  687. XSSFCell c = r.getCell(1);
  688. assertEquals("test\u00a0", c.getRichStringCellValue().getString());
  689. // It should be light green
  690. XSSFCellStyle cs = c.getCellStyle();
  691. assertEquals(42, cs.getFillForegroundColor());
  692. assertEquals(42, cs.getFillForegroundColorColor().getIndexed());
  693. assertNotNull(cs.getFillForegroundColorColor().getRgb());
  694. assertEquals("FFCCFFCC", cs.getFillForegroundColorColor().getARGBHex());
  695. wb.close();
  696. }
  697. /**
  698. * If the border colours are set with themes, then we
  699. * should still be able to get colours
  700. */
  701. @Test
  702. public void bug50846() throws Exception {
  703. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50846-border_colours.xlsx");
  704. XSSFSheet sheet = wb.getSheetAt(0);
  705. XSSFRow row = sheet.getRow(0);
  706. // Border from a theme, brown
  707. XSSFCell cellT = row.getCell(0);
  708. XSSFCellStyle styleT = cellT.getCellStyle();
  709. XSSFColor colorT = styleT.getBottomBorderXSSFColor();
  710. assertEquals(5, colorT.getTheme());
  711. assertEquals("FFC0504D", colorT.getARGBHex());
  712. // Border from a style direct, red
  713. XSSFCell cellS = row.getCell(1);
  714. XSSFCellStyle styleS = cellS.getCellStyle();
  715. XSSFColor colorS = styleS.getBottomBorderXSSFColor();
  716. assertEquals(0, colorS.getTheme());
  717. assertEquals("FFFF0000", colorS.getARGBHex());
  718. wb.close();
  719. }
  720. /**
  721. * Fonts where their colours come from the theme rather
  722. * then being set explicitly still should allow the
  723. * fetching of the RGB.
  724. */
  725. @SuppressWarnings("deprecation")
  726. @Test
  727. public void bug50784() throws Exception {
  728. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50784-font_theme_colours.xlsx");
  729. XSSFSheet s = wb.getSheetAt(0);
  730. XSSFRow r = s.getRow(0);
  731. // Column 1 has a font with regular colours
  732. XSSFCell cr = r.getCell(1);
  733. XSSFFont fr = wb.getFontAt( cr.getCellStyle().getFontIndex() );
  734. XSSFColor colr = fr.getXSSFColor();
  735. // No theme, has colours
  736. assertEquals(0, colr.getTheme());
  737. assertNotNull( colr.getRgb() );
  738. // Column 0 has a font with colours from a theme
  739. XSSFCell ct = r.getCell(0);
  740. XSSFFont ft = wb.getFontAt( ct.getCellStyle().getFontIndex() );
  741. XSSFColor colt = ft.getXSSFColor();
  742. // Has a theme, which has the colours on it
  743. assertEquals(9, colt.getTheme());
  744. XSSFColor themeC = wb.getTheme().getThemeColor(colt.getTheme());
  745. assertNotNull( themeC.getRgb() );
  746. assertNotNull( colt.getRgb() );
  747. assertEquals( themeC.getARGBHex(), colt.getARGBHex() ); // The same colour
  748. wb.close();
  749. }
  750. /**
  751. * New lines were being eaten when setting a font on
  752. * a rich text string
  753. */
  754. @Test
  755. public void bug48877() throws Exception {
  756. String text = "Use \n with word wrap on to create a new line.\n" +
  757. "This line finishes with two trailing spaces. ";
  758. XSSFWorkbook wb1 = new XSSFWorkbook();
  759. XSSFSheet sheet = wb1.createSheet();
  760. Font font1 = wb1.createFont();
  761. font1.setColor((short) 20);
  762. Font font2 = wb1.createFont();
  763. font2.setColor(Font.COLOR_RED);
  764. Font font3 = wb1.getFontAt((short)0);
  765. XSSFRow row = sheet.createRow(2);
  766. XSSFCell cell = row.createCell(2);
  767. XSSFRichTextString richTextString =
  768. wb1.getCreationHelper().createRichTextString(text);
  769. // Check the text has the newline
  770. assertEquals(text, richTextString.getString());
  771. // Apply the font
  772. richTextString.applyFont(font3);
  773. richTextString.applyFont(0, 3, font1);
  774. cell.setCellValue(richTextString);
  775. // To enable newlines you need set a cell styles with wrap=true
  776. CellStyle cs = wb1.createCellStyle();
  777. cs.setWrapText(true);
  778. cell.setCellStyle(cs);
  779. // Check the text has the
  780. assertEquals(text, cell.getStringCellValue());
  781. // Save the file and re-read it
  782. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  783. wb1.close();
  784. sheet = wb2.getSheetAt(0);
  785. row = sheet.getRow(2);
  786. cell = row.getCell(2);
  787. assertEquals(text, cell.getStringCellValue());
  788. // Now add a 2nd, and check again
  789. int fontAt = text.indexOf("\n", 6);
  790. cell.getRichStringCellValue().applyFont(10, fontAt+1, font2);
  791. assertEquals(text, cell.getStringCellValue());
  792. assertEquals(4, cell.getRichStringCellValue().numFormattingRuns());
  793. assertEquals("Use", cell.getRichStringCellValue().getCTRst().getRArray(0).getT());
  794. String r3 = cell.getRichStringCellValue().getCTRst().getRArray(2).getT();
  795. assertEquals("line.\n", r3.substring(r3.length()-6));
  796. // Save and re-check
  797. XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
  798. wb2.close();
  799. sheet = wb3.getSheetAt(0);
  800. row = sheet.getRow(2);
  801. cell = row.getCell(2);
  802. assertEquals(text, cell.getStringCellValue());
  803. wb3.close();
  804. // FileOutputStream out = new FileOutputStream("/tmp/test48877.xlsx");
  805. // wb.write(out);
  806. // out.close();
  807. }
  808. /**
  809. * Adding sheets when one has a table, then re-ordering
  810. */
  811. @Test
  812. public void bug50867() throws Exception {
  813. XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("50867_with_table.xlsx");
  814. assertEquals(3, wb1.getNumberOfSheets());
  815. XSSFSheet s1 = wb1.getSheetAt(0);
  816. XSSFSheet s2 = wb1.getSheetAt(1);
  817. XSSFSheet s3 = wb1.getSheetAt(2);
  818. assertEquals(1, s1.getTables().size());
  819. assertEquals(0, s2.getTables().size());
  820. assertEquals(0, s3.getTables().size());
  821. XSSFTable t = s1.getTables().get(0);
  822. assertEquals("Tabella1", t.getName());
  823. assertEquals("Tabella1", t.getDisplayName());
  824. assertEquals("A1:C3", t.getCTTable().getRef());
  825. // Add a sheet and re-order
  826. XSSFSheet s4 = wb1.createSheet("NewSheet");
  827. wb1.setSheetOrder(s4.getSheetName(), 0);
  828. // Check on tables
  829. assertEquals(1, s1.getTables().size());
  830. assertEquals(0, s2.getTables().size());
  831. assertEquals(0, s3.getTables().size());
  832. assertEquals(0, s4.getTables().size());
  833. // Refetch to get the new order
  834. s1 = wb1.getSheetAt(0);
  835. s2 = wb1.getSheetAt(1);
  836. s3 = wb1.getSheetAt(2);
  837. s4 = wb1.getSheetAt(3);
  838. assertEquals(0, s1.getTables().size());
  839. assertEquals(1, s2.getTables().size());
  840. assertEquals(0, s3.getTables().size());
  841. assertEquals(0, s4.getTables().size());
  842. // Save and re-load
  843. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  844. wb1.close();
  845. s1 = wb2.getSheetAt(0);
  846. s2 = wb2.getSheetAt(1);
  847. s3 = wb2.getSheetAt(2);
  848. s4 = wb2.getSheetAt(3);
  849. assertEquals(0, s1.getTables().size());
  850. assertEquals(1, s2.getTables().size());
  851. assertEquals(0, s3.getTables().size());
  852. assertEquals(0, s4.getTables().size());
  853. t = s2.getTables().get(0);
  854. assertEquals("Tabella1", t.getName());
  855. assertEquals("Tabella1", t.getDisplayName());
  856. assertEquals("A1:C3", t.getCTTable().getRef());
  857. // Add some more tables, and check
  858. t = s2.createTable();
  859. t.setName("New 2");
  860. t.setDisplayName("New 2");
  861. t = s3.createTable();
  862. t.setName("New 3");
  863. t.setDisplayName("New 3");
  864. XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
  865. wb2.close();
  866. s1 = wb3.getSheetAt(0);
  867. s2 = wb3.getSheetAt(1);
  868. s3 = wb3.getSheetAt(2);
  869. s4 = wb3.getSheetAt(3);
  870. assertEquals(0, s1.getTables().size());
  871. assertEquals(2, s2.getTables().size());
  872. assertEquals(1, s3.getTables().size());
  873. assertEquals(0, s4.getTables().size());
  874. t = s2.getTables().get(0);
  875. assertEquals("Tabella1", t.getName());
  876. assertEquals("Tabella1", t.getDisplayName());
  877. assertEquals("A1:C3", t.getCTTable().getRef());
  878. t = s2.getTables().get(1);
  879. assertEquals("New 2", t.getName());
  880. assertEquals("New 2", t.getDisplayName());
  881. t = s3.getTables().get(0);
  882. assertEquals("New 3", t.getName());
  883. assertEquals("New 3", t.getDisplayName());
  884. // Check the relationships
  885. assertEquals(0, s1.getRelations().size());
  886. assertEquals(3, s2.getRelations().size());
  887. assertEquals(1, s3.getRelations().size());
  888. assertEquals(0, s4.getRelations().size());
  889. assertEquals(
  890. XSSFRelation.PRINTER_SETTINGS.getContentType(),
  891. s2.getRelations().get(0).getPackagePart().getContentType()
  892. );
  893. assertEquals(
  894. XSSFRelation.TABLE.getContentType(),
  895. s2.getRelations().get(1).getPackagePart().getContentType()
  896. );
  897. assertEquals(
  898. XSSFRelation.TABLE.getContentType(),
  899. s2.getRelations().get(2).getPackagePart().getContentType()
  900. );
  901. assertEquals(
  902. XSSFRelation.TABLE.getContentType(),
  903. s3.getRelations().get(0).getPackagePart().getContentType()
  904. );
  905. assertEquals(
  906. "/xl/tables/table3.xml",
  907. s3.getRelations().get(0).getPackagePart().getPartName().toString()
  908. );
  909. wb3.close();
  910. }
  911. /**
  912. * Setting repeating rows and columns shouldn't break
  913. * any print settings that were there before
  914. */
  915. @SuppressWarnings("deprecation")
  916. @Test
  917. public void bug49253() throws Exception {
  918. XSSFWorkbook wb1 = new XSSFWorkbook();
  919. XSSFWorkbook wb2 = new XSSFWorkbook();
  920. // No print settings before repeating
  921. XSSFSheet s1 = wb1.createSheet();
  922. assertEquals(false, s1.getCTWorksheet().isSetPageSetup());
  923. assertEquals(true, s1.getCTWorksheet().isSetPageMargins());
  924. wb1.setRepeatingRowsAndColumns(0, 2, 3, 1, 2);
  925. assertEquals(true, s1.getCTWorksheet().isSetPageSetup());
  926. assertEquals(true, s1.getCTWorksheet().isSetPageMargins());
  927. PrintSetup ps1 = s1.getPrintSetup();
  928. assertEquals(false, ps1.getValidSettings());
  929. assertEquals(false, ps1.getLandscape());
  930. // Had valid print settings before repeating
  931. XSSFSheet s2 = wb2.createSheet();
  932. PrintSetup ps2 = s2.getPrintSetup();
  933. assertEquals(true, s2.getCTWorksheet().isSetPageSetup());
  934. assertEquals(true, s2.getCTWorksheet().isSetPageMargins());
  935. ps2.setLandscape(false);
  936. assertEquals(true, ps2.getValidSettings());
  937. assertEquals(false, ps2.getLandscape());
  938. wb2.setRepeatingRowsAndColumns(0, 2, 3, 1, 2);
  939. ps2 = s2.getPrintSetup();
  940. assertEquals(true, s2.getCTWorksheet().isSetPageSetup());
  941. assertEquals(true, s2.getCTWorksheet().isSetPageMargins());
  942. assertEquals(true, ps2.getValidSettings());
  943. assertEquals(false, ps2.getLandscape());
  944. wb1.close();
  945. wb2.close();
  946. }
  947. /**
  948. * Default Column style
  949. */
  950. @Test
  951. public void bug51037() throws Exception {
  952. XSSFWorkbook wb = new XSSFWorkbook();
  953. XSSFSheet s = wb.createSheet();
  954. CellStyle defaultStyle = wb.getCellStyleAt((short)0);
  955. assertEquals(0, defaultStyle.getIndex());
  956. CellStyle blueStyle = wb.createCellStyle();
  957. blueStyle.setFillForegroundColor(IndexedColors.AQUA.getIndex());
  958. blueStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
  959. assertEquals(1, blueStyle.getIndex());
  960. CellStyle pinkStyle = wb.createCellStyle();
  961. pinkStyle.setFillForegroundColor(IndexedColors.PINK.getIndex());
  962. pinkStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
  963. assertEquals(2, pinkStyle.getIndex());
  964. // Starts empty
  965. assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
  966. CTCols cols = s.getCTWorksheet().getColsArray(0);
  967. assertEquals(0, cols.sizeOfColArray());
  968. // Add some rows and columns
  969. XSSFRow r1 = s.createRow(0);
  970. XSSFRow r2 = s.createRow(1);
  971. r1.createCell(0);
  972. r1.createCell(2);
  973. r2.createCell(0);
  974. r2.createCell(3);
  975. // Check no style is there
  976. assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
  977. assertEquals(0, cols.sizeOfColArray());
  978. assertEquals(defaultStyle, s.getColumnStyle(0));
  979. assertEquals(defaultStyle, s.getColumnStyle(2));
  980. assertEquals(defaultStyle, s.getColumnStyle(3));
  981. // Apply the styles
  982. s.setDefaultColumnStyle(0, pinkStyle);
  983. s.setDefaultColumnStyle(3, blueStyle);
  984. // Check
  985. assertEquals(pinkStyle, s.getColumnStyle(0));
  986. assertEquals(defaultStyle, s.getColumnStyle(2));
  987. assertEquals(blueStyle, s.getColumnStyle(3));
  988. assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
  989. assertEquals(2, cols.sizeOfColArray());
  990. assertEquals(1, cols.getColArray(0).getMin());
  991. assertEquals(1, cols.getColArray(0).getMax());
  992. assertEquals(pinkStyle.getIndex(), cols.getColArray(0).getStyle());
  993. assertEquals(4, cols.getColArray(1).getMin());
  994. assertEquals(4, cols.getColArray(1).getMax());
  995. assertEquals(blueStyle.getIndex(), cols.getColArray(1).getStyle());
  996. // Save, re-load and re-check
  997. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  998. wb.close();
  999. s = wbBack.getSheetAt(0);
  1000. defaultStyle = wbBack.getCellStyleAt(defaultStyle.getIndex());
  1001. blueStyle = wbBack.getCellStyleAt(blueStyle.getIndex());
  1002. pinkStyle = wbBack.getCellStyleAt(pinkStyle.getIndex());
  1003. assertEquals(pinkStyle, s.getColumnStyle(0));
  1004. assertEquals(defaultStyle, s.getColumnStyle(2));
  1005. assertEquals(blueStyle, s.getColumnStyle(3));
  1006. wbBack.close();
  1007. }
  1008. /**
  1009. * Repeatedly writing a file.
  1010. * Something with the SharedStringsTable currently breaks...
  1011. */
  1012. @Test
  1013. public void bug46662() throws Exception {
  1014. // New file
  1015. XSSFWorkbook wb1 = new XSSFWorkbook();
  1016. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  1017. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  1018. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  1019. wb1.close();
  1020. // Simple file
  1021. XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx");
  1022. XSSFTestDataSamples.writeOutAndReadBack(wb2).close();
  1023. XSSFTestDataSamples.writeOutAndReadBack(wb2).close();
  1024. XSSFTestDataSamples.writeOutAndReadBack(wb2).close();
  1025. wb2.close();
  1026. // Complex file
  1027. // TODO
  1028. }
  1029. /**
  1030. * Colours and styles when the list has gaps in it
  1031. */
  1032. @Test
  1033. public void bug51222() throws Exception {
  1034. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51222.xlsx");
  1035. XSSFSheet s = wb.getSheetAt(0);
  1036. XSSFCell cA4_EEECE1 = s.getRow(3).getCell(0);
  1037. XSSFCell cA5_1F497D = s.getRow(4).getCell(0);
  1038. // Check the text
  1039. assertEquals("A4", cA4_EEECE1.getRichStringCellValue().getString());
  1040. assertEquals("A5", cA5_1F497D.getRichStringCellValue().getString());
  1041. // Check the styles assigned to them
  1042. assertEquals(4, cA4_EEECE1.getCTCell().getS());
  1043. assertEquals(5, cA5_1F497D.getCTCell().getS());
  1044. // Check we look up the correct style
  1045. assertEquals(4, cA4_EEECE1.getCellStyle().getIndex());
  1046. assertEquals(5, cA5_1F497D.getCellStyle().getIndex());
  1047. // Check the fills on them at the low level
  1048. assertEquals(5, cA4_EEECE1.getCellStyle().getCoreXf().getFillId());
  1049. assertEquals(6, cA5_1F497D.getCellStyle().getCoreXf().getFillId());
  1050. // These should reference themes 2 and 3
  1051. assertEquals(2, wb.getStylesSource().getFillAt(5).getCTFill().getPatternFill().getFgColor().getTheme());
  1052. assertEquals(3, wb.getStylesSource().getFillAt(6).getCTFill().getPatternFill().getFgColor().getTheme());
  1053. // Ensure we get the right colours for these themes
  1054. // TODO fix
  1055. // assertEquals("FFEEECE1", wb.getTheme().getThemeColor(2).getARGBHex());
  1056. // assertEquals("FF1F497D", wb.getTheme().getThemeColor(3).getARGBHex());
  1057. // Finally check the colours on the styles
  1058. // TODO fix
  1059. // assertEquals("FFEEECE1", cA4_EEECE1.getCellStyle().getFillForegroundXSSFColor().getARGBHex());
  1060. // assertEquals("FF1F497D", cA5_1F497D.getCellStyle().getFillForegroundXSSFColor().getARGBHex());
  1061. wb.close();
  1062. }
  1063. @Test
  1064. public void bug51470() throws Exception {
  1065. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51470.xlsx");
  1066. XSSFSheet sh0 = wb.getSheetAt(0);
  1067. XSSFSheet sh1 = wb.cloneSheet(0);
  1068. List<POIXMLDocumentPart> rels0 = sh0.getRelations();
  1069. List<POIXMLDocumentPart> rels1 = sh1.getRelations();
  1070. assertEquals(1, rels0.size());
  1071. assertEquals(1, rels1.size());
  1072. assertEquals(rels0.get(0).getPackageRelationship(), rels1.get(0).getPackageRelationship());
  1073. wb.close();
  1074. }
  1075. /**
  1076. * Add comments to Sheet 1, when Sheet 2 already has
  1077. * comments (so /xl/comments1.xml is taken)
  1078. */
  1079. @Test
  1080. public void bug51850() throws Exception {
  1081. XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("51850.xlsx");
  1082. XSSFSheet sh1 = wb1.getSheetAt(0);
  1083. XSSFSheet sh2 = wb1.getSheetAt(1);
  1084. // Sheet 2 has comments
  1085. assertNotNull(sh2.getCommentsTable(false));
  1086. assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments());
  1087. // Sheet 1 doesn't (yet)
  1088. assertNull(sh1.getCommentsTable(false));
  1089. // Try to add comments to Sheet 1
  1090. CreationHelper factory = wb1.getCreationHelper();
  1091. Drawing drawing = sh1.createDrawingPatriarch();
  1092. ClientAnchor anchor = factory.createClientAnchor();
  1093. anchor.setCol1(0);
  1094. anchor.setCol2(4);
  1095. anchor.setRow1(0);
  1096. anchor.setRow2(1);
  1097. Comment comment1 = drawing.createCellComment(anchor);
  1098. comment1.setString(
  1099. factory.createRichTextString("I like this cell. It's my favourite."));
  1100. comment1.setAuthor("Bob T. Fish");
  1101. anchor = factory.createClientAnchor();
  1102. anchor.setCol1(0);
  1103. anchor.setCol2(4);
  1104. anchor.setRow1(1);
  1105. anchor.setRow2(1);
  1106. Comment comment2 = drawing.createCellComment(anchor);
  1107. comment2.setString(
  1108. factory.createRichTextString("This is much less fun..."));
  1109. comment2.setAuthor("Bob T. Fish");
  1110. Cell c1 = sh1.getRow(0).createCell(4);
  1111. c1.setCellValue(2.3);
  1112. c1.setCellComment(comment1);
  1113. Cell c2 = sh1.getRow(0).createCell(5);
  1114. c2.setCellValue(2.1);
  1115. c2.setCellComment(comment2);
  1116. // Save and re-load
  1117. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  1118. wb1.close();
  1119. sh1 = wb2.getSheetAt(0);
  1120. sh2 = wb2.getSheetAt(1);
  1121. // Check the comments
  1122. assertNotNull(sh2.getCommentsTable(false));
  1123. assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments());
  1124. assertNotNull(sh1.getCommentsTable(false));
  1125. assertEquals(2, sh1.getCommentsTable(false).getNumberOfComments());
  1126. wb2.close();
  1127. }
  1128. /**
  1129. * Sheet names with a , in them
  1130. */
  1131. @Test
  1132. public void bug51963() throws Exception {
  1133. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51963.xlsx");
  1134. Sheet sheet = wb.getSheetAt(0);
  1135. assertEquals("Abc,1", sheet.getSheetName());
  1136. Name name = wb.getName("Intekon.ProdCodes");
  1137. assertEquals("'Abc,1'!$A$1:$A$2", name.getRefersToFormula());
  1138. @SuppressWarnings("deprecation")
  1139. AreaReference ref = new AreaReference(name.getRefersToFormula());
  1140. assertEquals(0, ref.getFirstCell().getRow());
  1141. assertEquals(0, ref.getFirstCell().getCol());
  1142. assertEquals(1, ref.getLastCell().getRow());
  1143. assertEquals(0, ref.getLastCell().getCol());
  1144. wb.close();
  1145. }
  1146. /**
  1147. * Sum across multiple workbooks
  1148. * eg =SUM($Sheet1.C1:$Sheet4.C1)
  1149. * DISABLED As we can't currently evaluate these
  1150. */
  1151. @Ignore
  1152. public void bug48703() throws Exception {
  1153. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48703.xlsx");
  1154. XSSFSheet sheet = wb.getSheetAt(0);
  1155. // Contains two forms, one with a range and one a list
  1156. XSSFRow r1 = sheet.getRow(0);
  1157. XSSFRow r2 = sheet.getRow(1);
  1158. XSSFCell c1 = r1.getCell(1);
  1159. XSSFCell c2 = r2.getCell(1);
  1160. assertEquals(20.0, c1.getNumericCellValue(), 0);
  1161. assertEquals("SUM(Sheet1!C1,Sheet2!C1,Sheet3!C1,Sheet4!C1)", c1.getCellFormula());
  1162. assertEquals(20.0, c2.getNumericCellValue(), 0);
  1163. assertEquals("SUM(Sheet1:Sheet4!C1)", c2.getCellFormula());
  1164. // Try evaluating both
  1165. XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb);
  1166. eval.evaluateFormulaCell(c1);
  1167. eval.evaluateFormulaCell(c2);
  1168. assertEquals(20.0, c1.getNumericCellValue(), 0);
  1169. assertEquals(20.0, c2.getNumericCellValue(), 0);
  1170. wb.close();
  1171. }
  1172. /**
  1173. * Bugzilla 51710: problems reading shared formuals from .xlsx
  1174. */
  1175. @Test
  1176. public void bug51710() throws Exception {
  1177. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51710.xlsx");
  1178. final String[] columns = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N"};
  1179. final int rowMax = 500; // bug triggers on row index 59
  1180. Sheet sheet = wb.getSheetAt(0);
  1181. // go through all formula cells
  1182. for (int rInd = 2; rInd <= rowMax; rInd++) {
  1183. Row row = sheet.getRow(rInd);
  1184. for (int cInd = 1; cInd <= 12; cInd++) {
  1185. Cell cell = row.getCell(cInd);
  1186. String formula = cell.getCellFormula();
  1187. CellReference ref = new CellReference(cell);
  1188. //simulate correct answer
  1189. String correct = "$A" + (rInd + 1) + "*" + columns[cInd] + "$2";
  1190. assertEquals("Incorrect formula in " + ref.formatAsString(), correct, formula);
  1191. }
  1192. }
  1193. wb.close();
  1194. }
  1195. /**
  1196. * Bug 53101:
  1197. */
  1198. @Test
  1199. public void bug5301() throws Exception {
  1200. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53101.xlsx");
  1201. FormulaEvaluator evaluator =
  1202. wb.getCreationHelper().createFormulaEvaluator();
  1203. // A1: SUM(B1: IZ1)
  1204. double a1Value =
  1205. evaluator.evaluate(wb.getSheetAt(0).getRow(0).getCell(0)).getNumberValue();
  1206. // Assert
  1207. assertEquals(259.0, a1Value, 0.0);
  1208. // KY: SUM(B1: IZ1)
  1209. /*double ky1Value =*/
  1210. evaluator.evaluate(wb.getSheetAt(0).getRow(0).getCell(310)).getNumberValue();
  1211. // Assert
  1212. assertEquals(259.0, a1Value, 0.0);
  1213. wb.close();
  1214. }
  1215. @Test
  1216. public void bug54436() throws Exception {
  1217. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54436.xlsx");
  1218. if(!WorkbookEvaluator.getSupportedFunctionNames().contains("GETPIVOTDATA")){
  1219. Function func = new Function() {
  1220. @Override
  1221. public ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
  1222. return ErrorEval.NA;
  1223. }
  1224. };
  1225. WorkbookEvaluator.registerFunction("GETPIVOTDATA", func);
  1226. }
  1227. wb.getCreationHelper().createFormulaEvaluator().evaluateAll();
  1228. wb.close();
  1229. }
  1230. /**
  1231. * Password Protected .xlsx files should give a helpful
  1232. * error message when called via WorkbookFactory with no password
  1233. */
  1234. @Test(expected=EncryptedDocumentException.class)
  1235. public void bug55692_poifs() throws Exception {
  1236. // Via a POIFSFileSystem
  1237. POIFSFileSystem fsP = new POIFSFileSystem(
  1238. POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));
  1239. try {
  1240. WorkbookFactory.create(fsP);
  1241. } finally {
  1242. fsP.close();
  1243. }
  1244. }
  1245. @Test
  1246. public void bug55692_stream() throws Exception {
  1247. // Directly on a Stream, will go via NPOIFS and spot it's
  1248. // actually a .xlsx file encrypted with the default password, and open
  1249. Workbook wb = WorkbookFactory.create(
  1250. POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));
  1251. assertNotNull(wb);
  1252. assertEquals(3, wb.getNumberOfSheets());
  1253. wb.close();
  1254. }
  1255. @Test
  1256. public void bug55692_npoifs() throws Exception {
  1257. // Via a NPOIFSFileSystem, will spot it's actually a .xlsx file
  1258. // encrypted with the default password, and open
  1259. NPOIFSFileSystem fsNP = new NPOIFSFileSystem(
  1260. POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));
  1261. Workbook wb = WorkbookFactory.create(fsNP);
  1262. assertNotNull(wb);
  1263. assertEquals(3, wb.getNumberOfSheets());
  1264. wb.close();
  1265. fsNP.close();
  1266. }
  1267. @Test
  1268. public void bug53282() throws Exception {
  1269. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53282b.xlsx");
  1270. Cell c = wb.getSheetAt(0).getRow(1).getCell(0);
  1271. assertEquals("#@_#", c.getStringCellValue());
  1272. assertEquals("http://invalid.uri", c.getHyperlink().getAddress());
  1273. wb.close();
  1274. }
  1275. /**
  1276. * Was giving NullPointerException
  1277. * at org.apache.poi.xssf.usermodel.XSSFWorkbook.onDocumentRead
  1278. * due to a lack of Styles Table
  1279. */
  1280. @Test
  1281. public void bug56278() throws Exception {
  1282. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56278.xlsx");
  1283. assertEquals(0, wb.getSheetIndex("Market Rates"));
  1284. // Save and re-check
  1285. Workbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1286. assertEquals(0, nwb.getSheetIndex("Market Rates"));
  1287. nwb.close();
  1288. wb.close();
  1289. }
  1290. @Test
  1291. public void bug56315() throws Exception {
  1292. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56315.xlsx");
  1293. Cell c = wb.getSheetAt(0).getRow(1).getCell(0);
  1294. CellValue cv = wb.getCreationHelper().createFormulaEvaluator().evaluate(c);
  1295. double rounded = cv.getNumberValue();
  1296. assertEquals(0.1, rounded, 0.0);
  1297. wb.close();
  1298. }
  1299. @Test
  1300. public void bug56468() throws Exception {
  1301. XSSFWorkbook wb = new XSSFWorkbook();
  1302. XSSFSheet sheet = wb.createSheet();
  1303. XSSFRow row = sheet.createRow(0);
  1304. XSSFCell cell = row.createCell(0);
  1305. cell.setCellValue("Hi");
  1306. sheet.setRepeatingRows(new CellRangeAddress(0, 0, 0, 0));
  1307. // small hack to try to make this test stable, previously it failed whenever the two written ZIP files had different file-creation
  1308. // dates stored.
  1309. // We try to do a loop until the current second changes in order to avoid problems with some date information that is written to the ZIP and thus
  1310. // causes differences
  1311. long start = System.currentTimeMillis()/1000;
  1312. while(System.currentTimeMillis()/1000 == start) {
  1313. Thread.sleep(10);
  1314. }
  1315. ByteArrayOutputStream bos = new ByteArrayOutputStream(8096);
  1316. wb.write(bos);
  1317. byte firstSave[] = bos.toByteArray();
  1318. bos.reset();
  1319. wb.write(bos);
  1320. byte secondSave[] = bos.toByteArray();
  1321. /*OutputStream stream = new FileOutputStream("C:\\temp\\poi.xlsx");
  1322. try {
  1323. wb.write(stream);
  1324. } finally {
  1325. stream.close();
  1326. }*/
  1327. assertArrayEquals("Had: \n" + Arrays.toString(firstSave) + " and \n" + Arrays.toString(secondSave),
  1328. firstSave, secondSave);
  1329. wb.close();
  1330. }
  1331. /**
  1332. * ISO-8601 style cell formats with a T in them, eg
  1333. * cell format of "yyyy-MM-ddTHH:mm:ss"
  1334. */
  1335. @Test
  1336. public void bug54034() throws IOException {
  1337. TimeZone tz = LocaleUtil.getUserTimeZone();
  1338. LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET"));
  1339. try {
  1340. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54034.xlsx");
  1341. Sheet sheet = wb.getSheet("Sheet1");
  1342. Row row = sheet.getRow(1);
  1343. Cell cell = row.getCell(2);
  1344. assertTrue(DateUtil.isCellDateFormatted(cell));
  1345. DataFormatter fmt = new DataFormatter();
  1346. assertEquals("yyyy\\-mm\\-dd\\Thh:mm", cell.getCellStyle().getDataFormatString());
  1347. assertEquals("2012-08-08T22:59", fmt.formatCellValue(cell));
  1348. wb.close();
  1349. } finally {
  1350. LocaleUtil.setUserTimeZone(tz);
  1351. }
  1352. }
  1353. @Test
  1354. public void testBug53798XLSX() throws IOException {
  1355. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx");
  1356. File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx");
  1357. bug53798Work(wb, xlsOutput);
  1358. wb.close();
  1359. }
  1360. @Ignore("Shifting rows is not yet implemented in SXSSFSheet")
  1361. @Test
  1362. public void testBug53798XLSXStream() throws IOException {
  1363. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx");
  1364. File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx");
  1365. SXSSFWorkbook wb2 = new SXSSFWorkbook(wb);
  1366. bug53798Work(wb2, xlsOutput);
  1367. wb2.close();
  1368. wb.close();
  1369. }
  1370. @Test
  1371. public void testBug53798XLS() throws IOException {
  1372. Workbook wb = HSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xls");
  1373. File xlsOutput = TempFile.createTempFile("testBug53798", ".xls");
  1374. bug53798Work(wb, xlsOutput);
  1375. wb.close();
  1376. }
  1377. /**
  1378. * SUMIF was throwing a NPE on some formulas
  1379. */
  1380. @Test
  1381. public void testBug56420SumIfNPE() throws Exception {
  1382. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56420.xlsx");
  1383. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  1384. Sheet sheet = wb.getSheetAt(0);
  1385. Row r = sheet.getRow(2);
  1386. Cell c = r.getCell(2);
  1387. assertEquals("SUMIF($A$1:$A$4,A3,$B$1:$B$4)", c.getCellFormula());
  1388. Cell eval = evaluator.evaluateInCell(c);
  1389. assertEquals(0.0, eval.getNumericCellValue(), 0.0001);
  1390. wb.close();
  1391. }
  1392. private void bug53798Work(Workbook wb, File xlsOutput) throws IOException {
  1393. Sheet testSheet = wb.getSheetAt(0);
  1394. testSheet.shiftRows(2, 2, 1);
  1395. saveAndReloadReport(wb, xlsOutput);
  1396. // 1) corrupted xlsx (unreadable data in the first row of a shifted group) already comes about
  1397. // when shifted by less than -1 negative amount (try -2)
  1398. testSheet.shiftRows(3, 3, -1);
  1399. saveAndReloadReport(wb, xlsOutput);
  1400. testSheet.shiftRows(2, 2, 1);
  1401. saveAndReloadReport(wb, xlsOutput);
  1402. Row newRow = null;
  1403. Cell newCell = null;
  1404. // 2) attempt to create a new row IN PLACE of a removed row by a negative shift causes corrupted
  1405. // xlsx file with unreadable data in the negative shifted row.
  1406. // NOTE it's ok to create any other row.
  1407. newRow = testSheet.createRow(3);
  1408. saveAndReloadReport(wb, xlsOutput);
  1409. newCell = newRow.createCell(0);
  1410. saveAndReloadReport(wb, xlsOutput);
  1411. newCell.setCellValue("new Cell in row "+newRow.getRowNum());
  1412. saveAndReloadReport(wb, xlsOutput);
  1413. // 3) once a negative shift has been made any attempt to shift another group of rows
  1414. // (note: outside of previously negative shifted rows) by a POSITIVE amount causes POI exception:
  1415. // org.apache.xmlbeans.impl.values.XmlValueDisconnectedException.
  1416. // NOTE: another negative shift on another group of rows is successful, provided no new rows in
  1417. // place of previously shifted rows were attempted to be created as explained above.
  1418. testSheet.shiftRows(6, 7, 1); // -- CHANGE the shift to positive once the behaviour of
  1419. // the above has been tested
  1420. saveAndReloadReport(wb, xlsOutput);
  1421. }
  1422. /**
  1423. * XSSFCell.typeMismatch on certain blank cells when formatting
  1424. * with DataFormatter
  1425. */
  1426. @Test
  1427. public void bug56702() throws Exception {
  1428. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56702.xlsx");
  1429. Sheet sheet = wb.getSheetAt(0);
  1430. // Get wrong cell by row 8 & column 7
  1431. Cell cell = sheet.getRow(8).getCell(7);
  1432. assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCellType());
  1433. // Check the value - will be zero as it is <c><v/></c>
  1434. assertEquals(0.0, cell.getNumericCellValue(), 0.001);
  1435. // Try to format
  1436. DataFormatter formatter = new DataFormatter();
  1437. formatter.formatCellValue(cell);
  1438. // Check the formatting
  1439. assertEquals("0", formatter.formatCellValue(cell));
  1440. wb.close();
  1441. }
  1442. /**
  1443. * Formulas which reference named ranges, either in other
  1444. * sheets, or workbook scoped but in other workbooks.
  1445. * Used to fail with with errors like
  1446. * org.apache.poi.ss.formula.FormulaParseException: Cell reference expected after sheet name at index 9
  1447. * org.apache.poi.ss.formula.FormulaParseException: Parse error near char 0 '[' in specified formula '[0]!NR_Global_B2'. Expected number, string, or defined name
  1448. */
  1449. @Test
  1450. public void bug56737() throws IOException {
  1451. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56737.xlsx");
  1452. // Check the named range definitions
  1453. Name nSheetScope = wb.getName("NR_To_A1");
  1454. Name nWBScope = wb.getName("NR_Global_B2");
  1455. assertNotNull(nSheetScope);
  1456. assertNotNull(nWBScope);
  1457. assertEquals("Defines!$A$1", nSheetScope.getRefersToFormula());
  1458. assertEquals("Defines!$B$2", nWBScope.getRefersToFormula());
  1459. // Check the different kinds of formulas
  1460. Sheet s = wb.getSheetAt(0);
  1461. Cell cRefSName = s.getRow(1).getCell(3);
  1462. Cell cRefWName = s.getRow(2).getCell(3);
  1463. assertEquals("Defines!NR_To_A1", cRefSName.getCellFormula());
  1464. // Note the formula, as stored in the file, has the external name index not filename
  1465. // TODO Provide a way to get the one with the filename
  1466. assertEquals("[0]!NR_Global_B2", cRefWName.getCellFormula());
  1467. // Try to evaluate them
  1468. FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator();
  1469. assertEquals("Test A1", eval.evaluate(cRefSName).getStringValue());
  1470. assertEquals(142, (int)eval.evaluate(cRefWName).getNumberValue());
  1471. // Try to evaluate everything
  1472. eval.evaluateAll();
  1473. wb.close();
  1474. }
  1475. private void saveAndReloadReport(Workbook wb, File outFile) throws IOException {
  1476. // run some method on the font to verify if it is "disconnected" already
  1477. //for(short i = 0;i < 256;i++)
  1478. {
  1479. Font font = wb.getFontAt((short)0);
  1480. if(font instanceof XSSFFont) {
  1481. XSSFFont xfont = (XSSFFont) wb.getFontAt((short)0);
  1482. CTFontImpl ctFont = (CTFontImpl) xfont.getCTFont();
  1483. assertEquals(0, ctFont.sizeOfBArray());
  1484. }
  1485. }
  1486. FileOutputStream fileOutStream = new FileOutputStream(outFile);
  1487. wb.write(fileOutStream);
  1488. fileOutStream.close();
  1489. //System.out.println("File \""+outFile.getName()+"\" has been saved successfully");
  1490. FileInputStream is = new FileInputStream(outFile);
  1491. try {
  1492. Workbook newWB = null;
  1493. try {
  1494. if(wb instanceof XSSFWorkbook) {
  1495. newWB = new XSSFWorkbook(is);
  1496. } else if(wb instanceof HSSFWorkbook) {
  1497. newWB = new HSSFWorkbook(is);
  1498. } else if(wb instanceof SXSSFWorkbook) {
  1499. newWB = new SXSSFWorkbook(new XSSFWorkbook(is));
  1500. } else {
  1501. throw new IllegalStateException("Unknown workbook: " + wb);
  1502. }
  1503. assertNotNull(newWB.getSheet("test"));
  1504. } finally {
  1505. newWB.close();
  1506. }
  1507. } finally {
  1508. is.close();
  1509. }
  1510. }
  1511. @Test
  1512. public void testBug56688_1() throws Exception {
  1513. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_1.xlsx");
  1514. checkValue(excel, "-1.0"); /* Not 0.0 because POI sees date "0" minus one month as invalid date, which is -1! */
  1515. excel.close();
  1516. }
  1517. @Test
  1518. public void testBug56688_2() throws Exception {
  1519. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_2.xlsx");
  1520. checkValue(excel, "#VALUE!");
  1521. excel.close();
  1522. }
  1523. @Test
  1524. public void testBug56688_3() throws Exception {
  1525. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_3.xlsx");
  1526. checkValue(excel, "#VALUE!");
  1527. excel.close();
  1528. }
  1529. @Test
  1530. public void testBug56688_4() throws Exception {
  1531. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_4.xlsx");
  1532. Calendar calendar = LocaleUtil.getLocaleCalendar();
  1533. calendar.add(Calendar.MONTH, 2);
  1534. double excelDate = DateUtil.getExcelDate(calendar.getTime());
  1535. NumberEval eval = new NumberEval(Math.floor(excelDate));
  1536. checkValue(excel, eval.getStringValue() + ".0");
  1537. excel.close();
  1538. }
  1539. /**
  1540. * New hyperlink with no initial cell reference, still need
  1541. * to be able to change it
  1542. * @throws IOException
  1543. */
  1544. @Test
  1545. public void testBug56527() throws IOException {
  1546. XSSFWorkbook wb = new XSSFWorkbook();
  1547. XSSFSheet sheet = wb.createSheet();
  1548. XSSFCreationHelper creationHelper = wb.getCreationHelper();
  1549. XSSFHyperlink hyperlink;
  1550. // Try with a cell reference
  1551. hyperlink = creationHelper.createHyperlink(Hyperlink.LINK_URL);
  1552. sheet.addHyperlink(hyperlink);
  1553. hyperlink.setAddress("http://myurl");
  1554. hyperlink.setCellReference("B4");
  1555. assertEquals(3, hyperlink.getFirstRow());
  1556. assertEquals(1, hyperlink.getFirstColumn());
  1557. assertEquals(3, hyperlink.getLastRow());
  1558. assertEquals(1, hyperlink.getLastColumn());
  1559. // Try with explicit rows / columns
  1560. hyperlink = creationHelper.createHyperlink(Hyperlink.LINK_URL);
  1561. sheet.addHyperlink(hyperlink);
  1562. hyperlink.setAddress("http://myurl");
  1563. hyperlink.setFirstRow(5);
  1564. hyperlink.setFirstColumn(3);
  1565. assertEquals(5, hyperlink.getFirstRow());
  1566. assertEquals(3, hyperlink.getFirstColumn());
  1567. assertEquals(5, hyperlink.getLastRow());
  1568. assertEquals(3, hyperlink.getLastColumn());
  1569. wb.close();
  1570. }
  1571. /**
  1572. * Shifting rows with a formula that references a
  1573. * function in another file
  1574. */
  1575. @Test
  1576. public void bug56502() throws Exception {
  1577. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56502.xlsx");
  1578. Sheet sheet = wb.getSheetAt(0);
  1579. Cell cFunc = sheet.getRow(3).getCell(0);
  1580. assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula());
  1581. Cell cRef = sheet.getRow(3).createCell(1);
  1582. cRef.setCellFormula("A3");
  1583. // Shift it down one row
  1584. sheet.shiftRows(1, sheet.getLastRowNum(), 1);
  1585. // Check the new formulas: Function won't change, Reference will
  1586. cFunc = sheet.getRow(4).getCell(0);
  1587. assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula());
  1588. cRef = sheet.getRow(4).getCell(1);
  1589. assertEquals("A4", cRef.getCellFormula());
  1590. wb.close();
  1591. }
  1592. @Test
  1593. public void bug54764() throws Exception {
  1594. OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("54764.xlsx");
  1595. // Check the core properties - will be found but empty, due
  1596. // to the expansion being too much to be considered valid
  1597. POIXMLProperties props = new POIXMLProperties(pkg);
  1598. assertEquals(null, props.getCoreProperties().getTitle());
  1599. assertEquals(null, props.getCoreProperties().getSubject());
  1600. assertEquals(null, props.getCoreProperties().getDescription());
  1601. // Now check the spreadsheet itself
  1602. try {
  1603. new XSSFWorkbook(pkg).close();
  1604. fail("Should fail as too much expansion occurs");
  1605. } catch(POIXMLException e) {
  1606. // Expected
  1607. }
  1608. pkg.close();
  1609. // Try with one with the entities in the Content Types
  1610. try {
  1611. XSSFTestDataSamples.openSamplePackage("54764-2.xlsx").close();
  1612. fail("Should fail as too much expansion occurs");
  1613. } catch(Exception e) {
  1614. // Expected
  1615. }
  1616. // Check we can still parse valid files after all that
  1617. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx");
  1618. assertEquals(3, wb.getNumberOfSheets());
  1619. wb.close();
  1620. }
  1621. /**
  1622. * CTDefinedNamesImpl should be included in the smaller
  1623. * poi-ooxml-schemas jar
  1624. */
  1625. @Test
  1626. public void bug57176() throws Exception {
  1627. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57176.xlsx");
  1628. CTDefinedNames definedNames = wb.getCTWorkbook().getDefinedNames();
  1629. List<CTDefinedName> definedNameList = definedNames.getDefinedNameList();
  1630. for (CTDefinedName defName : definedNameList) {
  1631. assertNotNull(defName.getName());
  1632. assertNotNull(defName.getStringValue());
  1633. }
  1634. assertEquals("TestDefinedName", definedNameList.get(0).getName());
  1635. wb.close();
  1636. }
  1637. /**
  1638. * .xlsb files are not supported, but we should generate a helpful
  1639. * error message if given one
  1640. */
  1641. @Test
  1642. public void bug56800_xlsb() throws Exception {
  1643. // Can be opened at the OPC level
  1644. OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("Simple.xlsb");
  1645. // XSSF Workbook gives helpful error
  1646. try {
  1647. new XSSFWorkbook(pkg).close();
  1648. fail(".xlsb files not supported");
  1649. } catch (XLSBUnsupportedException e) {
  1650. // Good, detected and warned
  1651. }
  1652. // Workbook Factory gives helpful error on package
  1653. try {
  1654. WorkbookFactory.create(pkg).close();
  1655. fail(".xlsb files not supported");
  1656. } catch (XLSBUnsupportedException e) {
  1657. // Good, detected and warned
  1658. }
  1659. // Workbook Factory gives helpful error on file
  1660. File xlsbFile = HSSFTestDataSamples.getSampleFile("Simple.xlsb");
  1661. try {
  1662. WorkbookFactory.create(xlsbFile).close();
  1663. fail(".xlsb files not supported");
  1664. } catch (XLSBUnsupportedException e) {
  1665. // Good, detected and warned
  1666. }
  1667. pkg.close();
  1668. }
  1669. private void checkValue(XSSFWorkbook excel, String expect) {
  1670. XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(excel);
  1671. evaluator.evaluateAll();
  1672. XSSFCell cell = excel.getSheetAt(0).getRow(1).getCell(1);
  1673. CellValue value = evaluator.evaluate(cell);
  1674. assertEquals(expect, value.formatAsString());
  1675. }
  1676. @Test
  1677. public void testBug57196() throws IOException {
  1678. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57196.xlsx");
  1679. Sheet sheet = wb.getSheet("Feuil1");
  1680. Row mod=sheet.getRow(1);
  1681. mod.getCell(1).setCellValue(3);
  1682. HSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
  1683. // FileOutputStream fileOutput = new FileOutputStream("/tmp/57196.xlsx");
  1684. // wb.write(fileOutput);
  1685. // fileOutput.close();
  1686. wb.close();
  1687. }
  1688. @Test
  1689. public void test57196_Detail() throws Exception {
  1690. XSSFWorkbook wb = new XSSFWorkbook();
  1691. XSSFSheet sheet = wb.createSheet("Sheet1");
  1692. XSSFRow row = sheet.createRow(0);
  1693. XSSFCell cell = row.createCell(0);
  1694. cell.setCellFormula("DEC2HEX(HEX2DEC(O8)-O2+D2)");
  1695. XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb);
  1696. CellValue cv = fe.evaluate(cell);
  1697. assertNotNull(cv);
  1698. wb.close();
  1699. }
  1700. @Test
  1701. public void test57196_Detail2() throws Exception {
  1702. XSSFWorkbook wb = new XSSFWorkbook();
  1703. XSSFSheet sheet = wb.createSheet("Sheet1");
  1704. XSSFRow row = sheet.createRow(0);
  1705. XSSFCell cell = row.createCell(0);
  1706. cell.setCellFormula("DEC2HEX(O2+D2)");
  1707. XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb);
  1708. CellValue cv = fe.evaluate(cell);
  1709. assertNotNull(cv);
  1710. wb.close();
  1711. }
  1712. @Test
  1713. public void test57196_WorkbookEvaluator() throws Exception {
  1714. String previousLogger = System.getProperty("org.apache.poi.util.POILogger");
  1715. //System.setProperty("org.apache.poi.util.POILogger", "org.apache.poi.util.SystemOutLogger");
  1716. //System.setProperty("poi.log.level", "3");
  1717. try {
  1718. XSSFWorkbook wb = new XSSFWorkbook();
  1719. XSSFSheet sheet = wb.createSheet("Sheet1");
  1720. XSSFRow row = sheet.createRow(0);
  1721. XSSFCell cell = row.createCell(0);
  1722. cell.setCellValue("0");
  1723. cell = row.createCell(1);
  1724. cell.setCellValue(0);
  1725. cell = row.createCell(2);
  1726. cell.setCellValue(0);
  1727. // simple formula worked
  1728. cell.setCellFormula("DEC2HEX(O2+D2)");
  1729. WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1730. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1731. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1732. // this already failed! Hex2Dec did not correctly handle RefEval
  1733. cell.setCellFormula("HEX2DEC(O8)");
  1734. workbookEvaluator.clearAllCachedResultValues();
  1735. workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1736. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1737. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1738. // slightly more complex one failed
  1739. cell.setCellFormula("HEX2DEC(O8)-O2+D2");
  1740. workbookEvaluator.clearAllCachedResultValues();
  1741. workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1742. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1743. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1744. // more complicated failed
  1745. cell.setCellFormula("DEC2HEX(HEX2DEC(O8)-O2+D2)");
  1746. workbookEvaluator.clearAllCachedResultValues();
  1747. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1748. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1749. // what other similar functions
  1750. cell.setCellFormula("DEC2BIN(O8)-O2+D2");
  1751. workbookEvaluator.clearAllCachedResultValues();
  1752. workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1753. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1754. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1755. // what other similar functions
  1756. cell.setCellFormula("DEC2BIN(A1)");
  1757. workbookEvaluator.clearAllCachedResultValues();
  1758. workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1759. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1760. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1761. // what other similar functions
  1762. cell.setCellFormula("BIN2DEC(B1)");
  1763. workbookEvaluator.clearAllCachedResultValues();
  1764. workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1765. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1766. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1767. wb.close();
  1768. } finally {
  1769. if(previousLogger == null) {
  1770. System.clearProperty("org.apache.poi.util.POILogger");
  1771. } else {
  1772. System.setProperty("org.apache.poi.util.POILogger", previousLogger);
  1773. }
  1774. System.clearProperty("poi.log.level");
  1775. }
  1776. }
  1777. /**
  1778. * A .xlsx file with no Shared Strings table should open fine
  1779. * in read-only mode
  1780. */
  1781. @SuppressWarnings("resource")
  1782. @Test
  1783. public void bug57482() throws Exception {
  1784. for (PackageAccess access : new PackageAccess[] {
  1785. PackageAccess.READ_WRITE, PackageAccess.READ
  1786. }) {
  1787. File file = HSSFTestDataSamples.getSampleFile("57482-OnlyNumeric.xlsx");
  1788. OPCPackage pkg = OPCPackage.open(file, access);
  1789. try {
  1790. // Try to open it and read the contents
  1791. XSSFWorkbook wb = new XSSFWorkbook(pkg);
  1792. assertNotNull(wb.getSharedStringSource());
  1793. assertEquals(0, wb.getSharedStringSource().getCount());
  1794. DataFormatter fmt = new DataFormatter();
  1795. XSSFSheet s = wb.getSheetAt(0);
  1796. assertEquals("1", fmt.formatCellValue(s.getRow(0).getCell(0)));
  1797. assertEquals("11", fmt.formatCellValue(s.getRow(0).getCell(1)));
  1798. assertEquals("5", fmt.formatCellValue(s.getRow(4).getCell(0)));
  1799. // Add a text cell
  1800. s.getRow(0).createCell(3).setCellValue("Testing");
  1801. assertEquals("Testing", fmt.formatCellValue(s.getRow(0).getCell(3)));
  1802. // Try to write-out and read again, should only work
  1803. // in read-write mode, not read-only mode
  1804. try {
  1805. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1806. if (access == PackageAccess.READ)
  1807. fail("Shouln't be able to write from read-only mode");
  1808. } catch (InvalidOperationException e) {
  1809. if (access == PackageAccess.READ) {
  1810. // Expected
  1811. } else {
  1812. // Shouldn't occur in write-mode
  1813. throw e;
  1814. }
  1815. }
  1816. // Check again
  1817. s = wb.getSheetAt(0);
  1818. assertEquals("1", fmt.formatCellValue(s.getRow(0).getCell(0)));
  1819. assertEquals("11", fmt.formatCellValue(s.getRow(0).getCell(1)));
  1820. assertEquals("5", fmt.formatCellValue(s.getRow(4).getCell(0)));
  1821. assertEquals("Testing", fmt.formatCellValue(s.getRow(0).getCell(3)));
  1822. } finally {
  1823. pkg.revert();
  1824. }
  1825. }
  1826. }
  1827. /**
  1828. * "Unknown error type: -60" fetching formula error value
  1829. */
  1830. @Test
  1831. public void bug57535() throws Exception {
  1832. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57535.xlsx");
  1833. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  1834. evaluator.clearAllCachedResultValues();
  1835. Sheet sheet = wb.getSheet("Sheet1");
  1836. Cell cell = sheet.getRow(5).getCell(4);
  1837. assertEquals(Cell.CELL_TYPE_FORMULA, cell.getCellType());
  1838. assertEquals("E4+E5", cell.getCellFormula());
  1839. CellValue value = evaluator.evaluate(cell);
  1840. assertEquals(Cell.CELL_TYPE_ERROR, value.getCellType());
  1841. assertEquals(-60, value.getErrorValue());
  1842. assertEquals("~CIRCULAR~REF~", FormulaError.forInt(value.getErrorValue()).getString());
  1843. assertEquals("CIRCULAR_REF", FormulaError.forInt(value.getErrorValue()).toString());
  1844. wb.close();
  1845. }
  1846. @Test
  1847. public void test57165() throws IOException {
  1848. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx");
  1849. try {
  1850. removeAllSheetsBut(3, wb);
  1851. wb.cloneSheet(0); // Throws exception here
  1852. wb.setSheetName(1, "New Sheet");
  1853. //saveWorkbook(wb, fileName);
  1854. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1855. try {
  1856. } finally {
  1857. wbBack.close();
  1858. }
  1859. } finally {
  1860. wb.close();
  1861. }
  1862. }
  1863. @Test
  1864. public void test57165_create() throws IOException {
  1865. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx");
  1866. try {
  1867. removeAllSheetsBut(3, wb);
  1868. wb.createSheet("newsheet"); // Throws exception here
  1869. wb.setSheetName(1, "New Sheet");
  1870. //saveWorkbook(wb, fileName);
  1871. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1872. try {
  1873. } finally {
  1874. wbBack.close();
  1875. }
  1876. } finally {
  1877. wb.close();
  1878. }
  1879. }
  1880. private static void removeAllSheetsBut(int sheetIndex, Workbook wb)
  1881. {
  1882. int sheetNb = wb.getNumberOfSheets();
  1883. // Move this sheet at the first position
  1884. wb.setSheetOrder(wb.getSheetName(sheetIndex), 0);
  1885. for (int sn = sheetNb - 1; sn > 0; sn--)
  1886. {
  1887. wb.removeSheetAt(sn);
  1888. }
  1889. }
  1890. /**
  1891. * Sums 2 plus the cell at the left, indirectly to avoid reference
  1892. * problems when deleting columns, conditionally to stop recursion
  1893. */
  1894. private static final String FORMULA1 =
  1895. "IF( INDIRECT( ADDRESS( ROW(), COLUMN()-1 ) ) = 0, 0,"
  1896. + "INDIRECT( ADDRESS( ROW(), COLUMN()-1 ) ) ) + 2";
  1897. /**
  1898. * Sums 2 plus the upper cell, indirectly to avoid reference
  1899. * problems when deleting rows, conditionally to stop recursion
  1900. */
  1901. private static final String FORMULA2 =
  1902. "IF( INDIRECT( ADDRESS( ROW()-1, COLUMN() ) ) = 0, 0,"
  1903. + "INDIRECT( ADDRESS( ROW()-1, COLUMN() ) ) ) + 2";
  1904. /**
  1905. * Expected:
  1906. * [ 0][ 2][ 4]
  1907. * @throws IOException
  1908. */
  1909. @Test
  1910. public void testBug56820_Formula1() throws IOException {
  1911. Workbook wb = new XSSFWorkbook();
  1912. try {
  1913. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  1914. Sheet sh = wb.createSheet();
  1915. sh.createRow(0).createCell(0).setCellValue(0.0d);
  1916. Cell formulaCell1 = sh.getRow(0).createCell(1);
  1917. Cell formulaCell2 = sh.getRow(0).createCell(2);
  1918. formulaCell1.setCellFormula(FORMULA1);
  1919. formulaCell2.setCellFormula(FORMULA1);
  1920. double A1 = evaluator.evaluate(formulaCell1).getNumberValue();
  1921. double A2 = evaluator.evaluate(formulaCell2).getNumberValue();
  1922. assertEquals(2, A1, 0);
  1923. assertEquals(4, A2, 0); //<-- FAILS EXPECTATIONS
  1924. } finally {
  1925. wb.close();
  1926. }
  1927. }
  1928. /**
  1929. * Expected:
  1930. * [ 0] <- number
  1931. * [ 2] <- formula
  1932. * [ 4] <- formula
  1933. * @throws IOException
  1934. */
  1935. @Test
  1936. public void testBug56820_Formula2() throws IOException {
  1937. Workbook wb = new XSSFWorkbook();
  1938. try {
  1939. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  1940. Sheet sh = wb.createSheet();
  1941. sh.createRow(0).createCell(0).setCellValue(0.0d);
  1942. Cell formulaCell1 = sh.createRow(1).createCell(0);
  1943. Cell formulaCell2 = sh.createRow(2).createCell(0);
  1944. formulaCell1.setCellFormula(FORMULA2);
  1945. formulaCell2.setCellFormula(FORMULA2);
  1946. double A1 = evaluator.evaluate(formulaCell1).getNumberValue();
  1947. double A2 = evaluator.evaluate(formulaCell2).getNumberValue(); //<-- FAILS EVALUATION
  1948. assertEquals(2, A1, 0);
  1949. assertEquals(4, A2, 0);
  1950. } finally {
  1951. wb.close();
  1952. }
  1953. }
  1954. @Test
  1955. public void test56467() throws IOException {
  1956. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("picture.xlsx");
  1957. try {
  1958. Sheet orig = wb.getSheetAt(0);
  1959. assertNotNull(orig);
  1960. Sheet sheet = wb.cloneSheet(0);
  1961. Drawing drawing = sheet.createDrawingPatriarch();
  1962. for (XSSFShape shape : ((XSSFDrawing) drawing).getShapes()) {
  1963. if (shape instanceof XSSFPicture) {
  1964. XSSFPictureData pictureData = ((XSSFPicture) shape).getPictureData();
  1965. assertNotNull(pictureData);
  1966. }
  1967. }
  1968. // OutputStream out = new FileOutputStream("/tmp/56467.xls");
  1969. // try {
  1970. // wb.write(out);
  1971. // } finally {
  1972. // out.close();
  1973. // }
  1974. } finally {
  1975. wb.close();
  1976. }
  1977. }
  1978. /**
  1979. * OOXML-Strict files
  1980. * Not currently working - namespace mis-match from XMLBeans
  1981. */
  1982. @Test
  1983. @Ignore("XMLBeans namespace mis-match on ooxml-strict files")
  1984. public void test57699() throws Exception {
  1985. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.strict.xlsx");
  1986. assertEquals(3, wb.getNumberOfSheets());
  1987. // TODO Check sheet contents
  1988. // TODO Check formula evaluation
  1989. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1990. assertEquals(3, wbBack.getNumberOfSheets());
  1991. // TODO Re-check sheet contents
  1992. // TODO Re-check formula evaluation
  1993. wb.close();
  1994. wbBack.close();
  1995. }
  1996. @Test
  1997. public void testBug56295_MergeXlslsWithStyles() throws IOException {
  1998. XSSFWorkbook xlsToAppendWorkbook = XSSFTestDataSamples.openSampleWorkbook("56295.xlsx");
  1999. XSSFSheet sheet = xlsToAppendWorkbook.getSheetAt(0);
  2000. XSSFRow srcRow = sheet.getRow(0);
  2001. XSSFCell oldCell = srcRow.getCell(0);
  2002. XSSFCellStyle cellStyle = oldCell.getCellStyle();
  2003. checkStyle(cellStyle);
  2004. // StylesTable table = xlsToAppendWorkbook.getStylesSource();
  2005. // List<XSSFCellFill> fills = table.getFills();
  2006. // System.out.println("Having " + fills.size() + " fills");
  2007. // for(XSSFCellFill fill : fills) {
  2008. // System.out.println("Fill: " + fill.getFillBackgroundColor() + "/" + fill.getFillForegroundColor());
  2009. // }
  2010. xlsToAppendWorkbook.close();
  2011. XSSFWorkbook targetWorkbook = new XSSFWorkbook();
  2012. XSSFSheet newSheet = targetWorkbook.createSheet(sheet.getSheetName());
  2013. XSSFRow destRow = newSheet.createRow(0);
  2014. XSSFCell newCell = destRow.createCell(0);
  2015. //newCell.getCellStyle().cloneStyleFrom(cellStyle);
  2016. CellStyle newCellStyle = targetWorkbook.createCellStyle();
  2017. newCellStyle.cloneStyleFrom(cellStyle);
  2018. newCell.setCellStyle(newCellStyle);
  2019. checkStyle(newCell.getCellStyle());
  2020. newCell.setCellValue(oldCell.getStringCellValue());
  2021. // OutputStream os = new FileOutputStream("output.xlsm");
  2022. // try {
  2023. // targetWorkbook.write(os);
  2024. // } finally {
  2025. // os.close();
  2026. // }
  2027. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(targetWorkbook);
  2028. XSSFCellStyle styleBack = wbBack.getSheetAt(0).getRow(0).getCell(0).getCellStyle();
  2029. checkStyle(styleBack);
  2030. targetWorkbook.close();
  2031. wbBack.close();
  2032. }
  2033. /**
  2034. * Paragraph with property BuFont but none of the properties
  2035. * BuNone, BuChar, and BuAutoNum, used to trigger a NPE
  2036. * Excel treats this as not-bulleted, so now do we
  2037. */
  2038. @Test
  2039. public void testBug57826() throws Exception {
  2040. XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("57826.xlsx");
  2041. assertTrue("no sheets in workbook", workbook.getNumberOfSheets() >= 1);
  2042. XSSFSheet sheet = workbook.getSheetAt(0);
  2043. XSSFDrawing drawing = sheet.getDrawingPatriarch();
  2044. assertNotNull(drawing);
  2045. List<XSSFShape> shapes = drawing.getShapes();
  2046. assertEquals(1, shapes.size());
  2047. assertTrue(shapes.get(0) instanceof XSSFSimpleShape);
  2048. XSSFSimpleShape shape = (XSSFSimpleShape)shapes.get(0);
  2049. // Used to throw a NPE
  2050. String text = shape.getText();
  2051. // No bulleting info included
  2052. assertEquals("test ok", text);
  2053. workbook.close();
  2054. }
  2055. private void checkStyle(XSSFCellStyle cellStyle) {
  2056. assertNotNull(cellStyle);
  2057. assertEquals(0, cellStyle.getFillForegroundColor());
  2058. assertNotNull(cellStyle.getFillForegroundXSSFColor());
  2059. XSSFColor fgColor = cellStyle.getFillForegroundColorColor();
  2060. assertNotNull(fgColor);
  2061. assertEquals("FF00FFFF", fgColor.getARGBHex());
  2062. assertEquals(0, cellStyle.getFillBackgroundColor());
  2063. assertNotNull(cellStyle.getFillBackgroundXSSFColor());
  2064. XSSFColor bgColor = cellStyle.getFillBackgroundColorColor();
  2065. assertNotNull(bgColor);
  2066. assertEquals("FF00FFFF", fgColor.getARGBHex());
  2067. }
  2068. @Test
  2069. public void bug57642() throws Exception {
  2070. XSSFWorkbook wb = new XSSFWorkbook();
  2071. XSSFSheet s = wb.createSheet("TestSheet");
  2072. XSSFCell c = s.createRow(0).createCell(0);
  2073. c.setCellFormula("ISERROR(TestSheet!A1)");
  2074. c = s.createRow(1).createCell(1);
  2075. c.setCellFormula("ISERROR(B2)");
  2076. wb.setSheetName(0, "CSN");
  2077. c = s.getRow(0).getCell(0);
  2078. assertEquals("ISERROR(CSN!A1)", c.getCellFormula());
  2079. c = s.getRow(1).getCell(1);
  2080. assertEquals("ISERROR(B2)", c.getCellFormula());
  2081. wb.close();
  2082. }
  2083. /**
  2084. * .xlsx supports 64000 cell styles, the style indexes after
  2085. * 32,767 must not be -32,768, then -32,767, -32,766
  2086. */
  2087. @Test
  2088. public void bug57880() throws Exception {
  2089. int numStyles = 33000;
  2090. XSSFWorkbook wb = new XSSFWorkbook();
  2091. //XSSFSheet s = wb.createSheet("TestSheet");
  2092. XSSFDataFormat fmt = wb.getCreationHelper().createDataFormat();
  2093. for (int i=1; i<numStyles; i++) {
  2094. short df = fmt.getFormat("test"+i);
  2095. // Format indexes will be wrapped beyond 32,676
  2096. assertEquals(164+i, df&0xffff);
  2097. // Create a style and use it
  2098. XSSFCellStyle style = wb.createCellStyle();
  2099. assertEquals(i, style.getUIndex());
  2100. style.setDataFormat(df);
  2101. /*XSSFCell c = s.createRow(i).createCell(0, Cell.CELL_TYPE_NUMERIC);
  2102. c.setCellStyle(style);
  2103. c.setCellValue(i);*/
  2104. }
  2105. // using temp file instead of ByteArrayOutputStream because of OOM in gump run
  2106. File tmp = TempFile.createTempFile("poi-test", ".bug57880");
  2107. OutputStream fos = new FileOutputStream(tmp);
  2108. try {
  2109. wb.write(fos);
  2110. } finally {
  2111. fos.close();
  2112. }
  2113. wb.close();
  2114. fmt = null; /*s = null;*/ wb = null;
  2115. // System.gc();
  2116. wb = new XSSFWorkbook(tmp);
  2117. fmt = wb.getCreationHelper().createDataFormat();
  2118. // s = wb.getSheetAt(0);
  2119. for (int i=1; i<numStyles; i++) {
  2120. XSSFCellStyle style = wb.getCellStyleAt((short)i);
  2121. assertNotNull(style);
  2122. assertEquals(i, style.getUIndex());
  2123. assertEquals(164+i, style.getDataFormat()&0xffff);
  2124. assertEquals("test"+i, style.getDataFormatString());
  2125. }
  2126. wb.close();
  2127. tmp.delete();
  2128. }
  2129. @Test
  2130. public void test56574() throws IOException {
  2131. runTest56574(false);
  2132. runTest56574(true);
  2133. }
  2134. @SuppressWarnings("deprecation")
  2135. private void runTest56574(boolean createRow) throws IOException {
  2136. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56574.xlsx");
  2137. Sheet sheet = wb.getSheet("Func");
  2138. assertNotNull(sheet);
  2139. Map<String, Object[]> data;
  2140. data = new TreeMap<String, Object[]>();
  2141. data.put("1", new Object[] {"ID", "NAME", "LASTNAME"});
  2142. data.put("2", new Object[] {2, "Amit", "Shukla"});
  2143. data.put("3", new Object[] {1, "Lokesh", "Gupta"});
  2144. data.put("4", new Object[] {4, "John", "Adwards"});
  2145. data.put("5", new Object[] {2, "Brian", "Schultz"});
  2146. Set<String> keyset = data.keySet();
  2147. int rownum = 1;
  2148. for (String key : keyset)
  2149. {
  2150. final Row row;
  2151. if(createRow) {
  2152. row = sheet.createRow(rownum++);
  2153. } else {
  2154. row = sheet.getRow(rownum++);
  2155. }
  2156. assertNotNull(row);
  2157. Object [] objArr = data.get(key);
  2158. int cellnum = 0;
  2159. for (Object obj : objArr)
  2160. {
  2161. Cell cell = row.getCell(cellnum);
  2162. if(cell == null){
  2163. cell = row.createCell(cellnum);
  2164. } else {
  2165. if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
  2166. cell.setCellFormula(null);
  2167. cell.getCellStyle().setDataFormat((short) 0);
  2168. }
  2169. }
  2170. if(obj instanceof String) {
  2171. cell.setCellValue((String)obj);
  2172. } else if(obj instanceof Integer) {
  2173. cell.setCellValue((Integer)obj);
  2174. }
  2175. cellnum++;
  2176. }
  2177. }
  2178. XSSFFormulaEvaluator.evaluateAllFormulaCells((XSSFWorkbook) wb);
  2179. wb.getCreationHelper().createFormulaEvaluator().evaluateAll();
  2180. CalculationChain chain = ((XSSFWorkbook)wb).getCalculationChain();
  2181. CTCalcCell[] cArray = chain.getCTCalcChain().getCArray();
  2182. for(CTCalcCell calc : cArray) {
  2183. // A2 to A6 should be gone
  2184. assertFalse(calc.getR().equals("A2"));
  2185. assertFalse(calc.getR().equals("A3"));
  2186. assertFalse(calc.getR().equals("A4"));
  2187. assertFalse(calc.getR().equals("A5"));
  2188. assertFalse(calc.getR().equals("A6"));
  2189. }
  2190. /*FileOutputStream out = new FileOutputStream(new File("C:\\temp\\56574.xlsx"));
  2191. try {
  2192. wb.write(out);
  2193. } finally {
  2194. out.close();
  2195. }*/
  2196. Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  2197. Sheet sheetBack = wbBack.getSheet("Func");
  2198. assertNotNull(sheetBack);
  2199. chain = ((XSSFWorkbook)wbBack).getCalculationChain();
  2200. cArray = chain.getCTCalcChain().getCArray();
  2201. for(CTCalcCell calc : cArray) {
  2202. // A2 to A6 should be gone
  2203. assertFalse(calc.getR().equals("A2"));
  2204. assertFalse(calc.getR().equals("A3"));
  2205. assertFalse(calc.getR().equals("A4"));
  2206. assertFalse(calc.getR().equals("A5"));
  2207. assertFalse(calc.getR().equals("A6"));
  2208. }
  2209. wbBack.close();
  2210. wb.close();
  2211. }
  2212. /**
  2213. * Excel 2007 generated Macro-Enabled .xlsm file
  2214. */
  2215. @Test
  2216. public void bug57181() throws Exception {
  2217. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57181.xlsm");
  2218. assertEquals(9, wb.getNumberOfSheets());
  2219. wb.close();
  2220. }
  2221. @Test
  2222. public void bug52111() throws Exception {
  2223. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("Intersection-52111-xssf.xlsx");
  2224. Sheet s = wb.getSheetAt(0);
  2225. assertFormula(wb, s.getRow(2).getCell(0), "(C2:D3 D3:E4)", "4.0");
  2226. assertFormula(wb, s.getRow(6).getCell(0), "Tabelle2!E:E Tabelle2!11:11", "5.0");
  2227. assertFormula(wb, s.getRow(8).getCell(0), "Tabelle2!E:F Tabelle2!11:12", null);
  2228. wb.close();
  2229. }
  2230. private void assertFormula(Workbook wb, Cell intF, String expectedFormula, String expectedResultOrNull) {
  2231. assertEquals(Cell.CELL_TYPE_FORMULA, intF.getCellType());
  2232. if (null == expectedResultOrNull) {
  2233. assertEquals(Cell.CELL_TYPE_ERROR, intF.getCachedFormulaResultType());
  2234. expectedResultOrNull = "#VALUE!";
  2235. }
  2236. else {
  2237. assertEquals(Cell.CELL_TYPE_NUMERIC, intF.getCachedFormulaResultType());
  2238. }
  2239. assertEquals(expectedFormula, intF.getCellFormula());
  2240. // Check we can evaluate it correctly
  2241. FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator();
  2242. assertEquals(expectedResultOrNull, eval.evaluate(intF).formatAsString());
  2243. }
  2244. @Test
  2245. public void test48962() throws Exception {
  2246. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("48962.xlsx");
  2247. Sheet sh = wb.getSheetAt(0);
  2248. Row row = sh.getRow(1);
  2249. Cell cell = row.getCell(0);
  2250. CellStyle style = cell.getCellStyle();
  2251. assertNotNull(style);
  2252. // color index
  2253. assertEquals(64, style.getFillBackgroundColor());
  2254. XSSFColor color = ((XSSFCellStyle)style).getFillBackgroundXSSFColor();
  2255. assertNotNull(color);
  2256. // indexed color
  2257. assertEquals(64, color.getIndexed());
  2258. assertEquals(64, color.getIndex());
  2259. // not an RGB color
  2260. assertFalse(color.isRGB());
  2261. assertNull(color.getRGB());
  2262. wb.close();
  2263. }
  2264. @Test
  2265. public void test50755_workday_formula_example() throws Exception {
  2266. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50755_workday_formula_example.xlsx");
  2267. Sheet sheet = wb.getSheet("Sheet1");
  2268. for(Row aRow : sheet) {
  2269. Cell cell = aRow.getCell(1);
  2270. if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
  2271. String formula = cell.getCellFormula();
  2272. //System.out.println("formula: " + formula);
  2273. assertNotNull(formula);
  2274. assertTrue(formula.contains("WORKDAY"));
  2275. } else {
  2276. assertNotNull(cell.toString());
  2277. }
  2278. }
  2279. wb.close();
  2280. }
  2281. @Test
  2282. public void test51626() throws Exception {
  2283. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51626.xlsx");
  2284. assertNotNull(wb);
  2285. wb.close();
  2286. InputStream stream = HSSFTestDataSamples.openSampleFileStream("51626.xlsx");
  2287. wb = WorkbookFactory.create(stream);
  2288. stream.close();
  2289. wb.close();
  2290. wb = XSSFTestDataSamples.openSampleWorkbook("51626_contact.xlsx");
  2291. assertNotNull(wb);
  2292. wb.close();
  2293. stream = HSSFTestDataSamples.openSampleFileStream("51626_contact.xlsx");
  2294. wb = WorkbookFactory.create(stream);
  2295. stream.close();
  2296. wb.close();
  2297. }
  2298. @Test
  2299. public void test51451() throws IOException {
  2300. Workbook wb = new XSSFWorkbook();
  2301. Sheet sh = wb.createSheet();
  2302. Row row = sh.createRow(0);
  2303. Cell cell = row.createCell(0);
  2304. cell.setCellValue(239827342);
  2305. CellStyle style = wb.createCellStyle();
  2306. //style.setHidden(false);
  2307. DataFormat excelFormat = wb.createDataFormat();
  2308. style.setDataFormat(excelFormat.getFormat("#,##0"));
  2309. sh.setDefaultColumnStyle(0, style);
  2310. // FileOutputStream out = new FileOutputStream("/tmp/51451.xlsx");
  2311. // wb.write(out);
  2312. // out.close();
  2313. wb.close();
  2314. }
  2315. @Test
  2316. public void test53105() throws IOException {
  2317. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53105.xlsx");
  2318. assertNotNull(wb);
  2319. // Act
  2320. // evaluate SUM('Skye Lookup Input'!A4:XFD4), cells in range each contain "1"
  2321. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  2322. double numericValue = evaluator.evaluate(wb.getSheetAt(0).getRow(1).getCell(0)).getNumberValue();
  2323. // Assert
  2324. assertEquals(16384.0, numericValue, 0.0);
  2325. wb.close();
  2326. }
  2327. @Test
  2328. public void test58315() throws IOException {
  2329. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58315.xlsx");
  2330. Cell cell = wb.getSheetAt(0).getRow(0).getCell(0);
  2331. assertNotNull(cell);
  2332. StringBuilder tmpCellContent = new StringBuilder(cell.getStringCellValue());
  2333. XSSFRichTextString richText = (XSSFRichTextString) cell.getRichStringCellValue();
  2334. for (int i = richText.length() - 1; i >= 0; i--) {
  2335. Font f = richText.getFontAtIndex(i);
  2336. if (f != null && f.getStrikeout()) {
  2337. tmpCellContent.deleteCharAt(i);
  2338. }
  2339. }
  2340. String result = tmpCellContent.toString();
  2341. assertEquals("320 350", result);
  2342. wb.close();
  2343. }
  2344. @Test
  2345. public void test55406() {
  2346. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("55406_Conditional_formatting_sample.xlsx");
  2347. Sheet sheet = wb.getSheetAt(0);
  2348. Cell cellA1 = sheet.getRow(0).getCell(0);
  2349. Cell cellA2 = sheet.getRow(1).getCell(0);
  2350. assertEquals(0, cellA1.getCellStyle().getFillForegroundColor());
  2351. assertEquals("FFFDFDFD", ((XSSFColor)cellA1.getCellStyle().getFillForegroundColorColor()).getARGBHex());
  2352. assertEquals(0, cellA2.getCellStyle().getFillForegroundColor());
  2353. assertEquals("FFFDFDFD", ((XSSFColor)cellA2.getCellStyle().getFillForegroundColorColor()).getARGBHex());
  2354. SheetConditionalFormatting cond = sheet.getSheetConditionalFormatting();
  2355. assertEquals(2, cond.getNumConditionalFormattings());
  2356. assertEquals(1, cond.getConditionalFormattingAt(0).getNumberOfRules());
  2357. assertEquals(64, cond.getConditionalFormattingAt(0).getRule(0).getPatternFormatting().getFillForegroundColor());
  2358. assertEquals("ISEVEN(ROW())", cond.getConditionalFormattingAt(0).getRule(0).getFormula1());
  2359. assertNull(((XSSFColor)cond.getConditionalFormattingAt(0).getRule(0).getPatternFormatting().getFillForegroundColorColor()).getARGBHex());
  2360. assertEquals(1, cond.getConditionalFormattingAt(1).getNumberOfRules());
  2361. assertEquals(64, cond.getConditionalFormattingAt(1).getRule(0).getPatternFormatting().getFillForegroundColor());
  2362. assertEquals("ISEVEN(ROW())", cond.getConditionalFormattingAt(1).getRule(0).getFormula1());
  2363. assertNull(((XSSFColor)cond.getConditionalFormattingAt(1).getRule(0).getPatternFormatting().getFillForegroundColorColor()).getARGBHex());
  2364. }
  2365. }