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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497
  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.apache.poi.openxml4j.opc.TestContentType.isOldXercesActive;
  17. import static org.junit.Assert.assertArrayEquals;
  18. import static org.junit.Assert.assertEquals;
  19. import static org.junit.Assert.assertFalse;
  20. import static org.junit.Assert.assertNotEquals;
  21. import static org.junit.Assert.assertNotNull;
  22. import static org.junit.Assert.assertNull;
  23. import static org.junit.Assert.assertTrue;
  24. import static org.junit.Assert.fail;
  25. import java.io.ByteArrayInputStream;
  26. import java.io.ByteArrayOutputStream;
  27. import java.io.File;
  28. import java.io.FileInputStream;
  29. import java.io.FileOutputStream;
  30. import java.io.IOException;
  31. import java.io.InputStream;
  32. import java.io.OutputStream;
  33. import java.nio.charset.StandardCharsets;
  34. import java.time.Duration;
  35. import java.time.Instant;
  36. import java.util.Arrays;
  37. import java.util.Calendar;
  38. import java.util.HashMap;
  39. import java.util.HashSet;
  40. import java.util.List;
  41. import java.util.Map;
  42. import java.util.Set;
  43. import java.util.TimeZone;
  44. import java.util.TreeMap;
  45. import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
  46. import org.apache.commons.compress.archivers.zip.ZipFile;
  47. import org.apache.poi.POIDataSamples;
  48. import org.apache.poi.common.usermodel.HyperlinkType;
  49. import org.apache.poi.hssf.HSSFITestDataProvider;
  50. import org.apache.poi.hssf.HSSFTestDataSamples;
  51. import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
  52. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  53. import org.apache.poi.ooxml.POIXMLDocumentPart;
  54. import org.apache.poi.ooxml.POIXMLDocumentPart.RelationPart;
  55. import org.apache.poi.ooxml.POIXMLException;
  56. import org.apache.poi.ooxml.POIXMLProperties;
  57. import org.apache.poi.ooxml.util.DocumentHelper;
  58. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  59. import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
  60. import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
  61. import org.apache.poi.openxml4j.opc.OPCPackage;
  62. import org.apache.poi.openxml4j.opc.PackageAccess;
  63. import org.apache.poi.openxml4j.opc.PackagePart;
  64. import org.apache.poi.openxml4j.opc.PackageRelationship;
  65. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  66. import org.apache.poi.openxml4j.util.ZipSecureFile;
  67. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  68. import org.apache.poi.ss.ITestDataProvider;
  69. import org.apache.poi.ss.SpreadsheetVersion;
  70. import org.apache.poi.ss.formula.ConditionalFormattingEvaluator;
  71. import org.apache.poi.ss.formula.EvaluationConditionalFormatRule;
  72. import org.apache.poi.ss.formula.FormulaParser;
  73. import org.apache.poi.ss.formula.FormulaRenderer;
  74. import org.apache.poi.ss.formula.FormulaShifter;
  75. import org.apache.poi.ss.formula.FormulaType;
  76. import org.apache.poi.ss.formula.WorkbookEvaluator;
  77. import org.apache.poi.ss.formula.WorkbookEvaluatorProvider;
  78. import org.apache.poi.ss.formula.eval.ErrorEval;
  79. import org.apache.poi.ss.formula.eval.NumberEval;
  80. import org.apache.poi.ss.formula.functions.Function;
  81. import org.apache.poi.ss.formula.ptg.Ptg;
  82. import org.apache.poi.ss.usermodel.*;
  83. import org.apache.poi.ss.util.AreaReference;
  84. import org.apache.poi.ss.util.CellAddress;
  85. import org.apache.poi.ss.util.CellRangeAddress;
  86. import org.apache.poi.ss.util.CellReference;
  87. import org.apache.poi.ss.util.CellUtil;
  88. import org.apache.poi.util.LocaleUtil;
  89. import org.apache.poi.util.NullOutputStream;
  90. import org.apache.poi.util.POILogFactory;
  91. import org.apache.poi.util.POILogger;
  92. import org.apache.poi.util.TempFile;
  93. import org.apache.poi.util.XMLHelper;
  94. import org.apache.poi.xssf.SXSSFITestDataProvider;
  95. import org.apache.poi.xssf.XLSBUnsupportedException;
  96. import org.apache.poi.xssf.XSSFITestDataProvider;
  97. import org.apache.poi.xssf.XSSFTestDataSamples;
  98. import org.apache.poi.xssf.model.CalculationChain;
  99. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  100. import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill;
  101. import org.apache.xmlbeans.XmlException;
  102. import org.junit.Ignore;
  103. import org.junit.Test;
  104. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcCell;
  105. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols;
  106. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName;
  107. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedNames;
  108. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTMergeCell;
  109. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTMergeCells;
  110. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
  111. import org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTFontImpl;
  112. import org.xml.sax.InputSource;
  113. import org.xml.sax.SAXParseException;
  114. import org.xml.sax.XMLReader;
  115. public final class TestXSSFBugs extends BaseTestBugzillaIssues {
  116. private static POILogger LOG = POILogFactory.getLogger(TestXSSFBugs.class);
  117. public TestXSSFBugs() {
  118. super(XSSFITestDataProvider.instance);
  119. }
  120. /**
  121. * test writing a file with large number of unique strings,
  122. * open resulting file in Excel to check results!
  123. */
  124. @Test
  125. public void bug15375_2() throws IOException {
  126. bug15375(1000);
  127. }
  128. /**
  129. * Named ranges had the right reference, but
  130. * the wrong sheet name
  131. */
  132. @Test
  133. public void bug45430() throws IOException {
  134. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("45430.xlsx")) {
  135. assertFalse(wb.isMacroEnabled());
  136. assertEquals(3, wb.getNumberOfNames());
  137. assertEquals(0, wb.getName("SheetAA1").getCTName().getLocalSheetId());
  138. assertFalse(wb.getName("SheetAA1").getCTName().isSetLocalSheetId());
  139. assertEquals("SheetA!$A$1", wb.getName("SheetAA1").getRefersToFormula());
  140. assertEquals("SheetA", wb.getName("SheetAA1").getSheetName());
  141. assertEquals(0, wb.getName("SheetBA1").getCTName().getLocalSheetId());
  142. assertFalse(wb.getName("SheetBA1").getCTName().isSetLocalSheetId());
  143. assertEquals("SheetB!$A$1", wb.getName("SheetBA1").getRefersToFormula());
  144. assertEquals("SheetB", wb.getName("SheetBA1").getSheetName());
  145. assertEquals(0, wb.getName("SheetCA1").getCTName().getLocalSheetId());
  146. assertFalse(wb.getName("SheetCA1").getCTName().isSetLocalSheetId());
  147. assertEquals("SheetC!$A$1", wb.getName("SheetCA1").getRefersToFormula());
  148. assertEquals("SheetC", wb.getName("SheetCA1").getSheetName());
  149. // Save and re-load, still there
  150. try (XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb)) {
  151. assertEquals(3, nwb.getNumberOfNames());
  152. assertEquals("SheetA!$A$1", nwb.getName("SheetAA1").getRefersToFormula());
  153. }
  154. }
  155. }
  156. /**
  157. * We should carry vba macros over after save
  158. */
  159. @Test
  160. public void bug45431() throws IOException, InvalidFormatException {
  161. XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("45431.xlsm");
  162. OPCPackage pkg1 = wb1.getPackage();
  163. assertTrue(wb1.isMacroEnabled());
  164. // Check the various macro related bits can be found
  165. PackagePart vba = pkg1.getPart(
  166. PackagingURIHelper.createPartName("/xl/vbaProject.bin")
  167. );
  168. assertNotNull(vba);
  169. // And the drawing bit
  170. PackagePart drw = pkg1.getPart(
  171. PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
  172. );
  173. assertNotNull(drw);
  174. // Save and re-open, both still there
  175. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  176. pkg1.close();
  177. wb1.close();
  178. OPCPackage pkg2 = wb2.getPackage();
  179. assertTrue(wb2.isMacroEnabled());
  180. vba = pkg2.getPart(
  181. PackagingURIHelper.createPartName("/xl/vbaProject.bin")
  182. );
  183. assertNotNull(vba);
  184. drw = pkg2.getPart(
  185. PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
  186. );
  187. assertNotNull(drw);
  188. // And again, just to be sure
  189. XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
  190. pkg2.close();
  191. wb2.close();
  192. OPCPackage pkg3 = wb3.getPackage();
  193. assertTrue(wb3.isMacroEnabled());
  194. vba = pkg3.getPart(
  195. PackagingURIHelper.createPartName("/xl/vbaProject.bin")
  196. );
  197. assertNotNull(vba);
  198. drw = pkg3.getPart(
  199. PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
  200. );
  201. assertNotNull(drw);
  202. pkg3.close();
  203. wb3.close();
  204. }
  205. @Test
  206. public void bug47504() throws IOException {
  207. XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47504.xlsx");
  208. assertEquals(1, wb1.getNumberOfSheets());
  209. XSSFSheet sh = wb1.getSheetAt(0);
  210. XSSFDrawing drawing = sh.createDrawingPatriarch();
  211. List<RelationPart> rels = drawing.getRelationParts();
  212. assertEquals(1, rels.size());
  213. assertEquals("Sheet1!A1", rels.get(0).getRelationship().getTargetURI().getFragment());
  214. // And again, just to be sure
  215. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  216. wb1.close();
  217. assertEquals(1, wb2.getNumberOfSheets());
  218. sh = wb2.getSheetAt(0);
  219. drawing = sh.createDrawingPatriarch();
  220. rels = drawing.getRelationParts();
  221. assertEquals(1, rels.size());
  222. assertEquals("Sheet1!A1", rels.get(0).getRelationship().getTargetURI().getFragment());
  223. wb2.close();
  224. }
  225. /**
  226. * Excel will sometimes write a button with a textbox
  227. * containing &gt;br&lt; (not closed!).
  228. * Clearly Excel shouldn't do this, but test that we can
  229. * read the file despite the naughtiness
  230. */
  231. @Test
  232. public void bug49020() throws IOException {
  233. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("BrNotClosed.xlsx")) {
  234. assertNotNull(wb);
  235. }
  236. }
  237. /**
  238. * ensure that CTPhoneticPr is loaded by the ooxml test suite so that it is included in poi-ooxml-schemas
  239. */
  240. @Test
  241. public void bug49325() throws IOException {
  242. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49325.xlsx")) {
  243. CTWorksheet sh = wb.getSheetAt(0).getCTWorksheet();
  244. assertNotNull(sh.getPhoneticPr());
  245. }
  246. }
  247. /**
  248. * Names which are defined with a Sheet
  249. * should return that sheet index properly
  250. */
  251. @Test
  252. public void bug48923() throws IOException {
  253. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48923.xlsx")) {
  254. assertEquals(4, wb.getNumberOfNames());
  255. Name b1 = wb.getName("NameB1");
  256. Name b2 = wb.getName("NameB2");
  257. Name sheet2 = wb.getName("NameSheet2");
  258. Name test = wb.getName("Test");
  259. assertNotNull(b1);
  260. assertEquals("NameB1", b1.getNameName());
  261. assertEquals("Sheet1", b1.getSheetName());
  262. assertEquals(-1, b1.getSheetIndex());
  263. assertNotNull(b2);
  264. assertEquals("NameB2", b2.getNameName());
  265. assertEquals("Sheet1", b2.getSheetName());
  266. assertEquals(-1, b2.getSheetIndex());
  267. assertNotNull(sheet2);
  268. assertEquals("NameSheet2", sheet2.getNameName());
  269. assertEquals("Sheet2", sheet2.getSheetName());
  270. assertEquals(-1, sheet2.getSheetIndex());
  271. assertNotNull(test);
  272. assertEquals("Test", test.getNameName());
  273. assertEquals("Sheet1", test.getSheetName());
  274. assertEquals(-1, test.getSheetIndex());
  275. }
  276. }
  277. /**
  278. * Problem with evaluation formulas due to
  279. * NameXPtgs.
  280. * Blows up on:
  281. * IF(B6= (ROUNDUP(B6,0) + ROUNDDOWN(B6,0))/2, MROUND(B6,2),ROUND(B6,0))
  282. * <p>
  283. * TODO: delete this test case when MROUND and VAR are implemented
  284. */
  285. @Test
  286. public void bug48539() throws IOException {
  287. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48539.xlsx")) {
  288. assertEquals(3, wb.getNumberOfSheets());
  289. assertEquals(0, wb.getNumberOfNames());
  290. // Try each cell individually
  291. XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb);
  292. for (int i = 0; i < wb.getNumberOfSheets(); i++) {
  293. Sheet s = wb.getSheetAt(i);
  294. for (Row r : s) {
  295. for (Cell c : r) {
  296. if (c.getCellType() == CellType.FORMULA) {
  297. CellValue cv = eval.evaluate(c);
  298. if (cv.getCellType() == CellType.NUMERIC) {
  299. // assert that the calculated value agrees with
  300. // the cached formula result calculated by Excel
  301. String formula = c.getCellFormula();
  302. double cachedFormulaResult = c.getNumericCellValue();
  303. double evaluatedFormulaResult = cv.getNumberValue();
  304. assertEquals(formula, cachedFormulaResult, evaluatedFormulaResult, 1E-7);
  305. }
  306. }
  307. }
  308. }
  309. }
  310. // Now all of them
  311. XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
  312. }
  313. }
  314. /**
  315. * Foreground colours should be found even if
  316. * a theme is used
  317. */
  318. @Test
  319. public void bug48779() throws IOException {
  320. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx")) {
  321. XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0);
  322. XSSFCellStyle cs = cell.getCellStyle();
  323. assertNotNull(cs);
  324. assertEquals(1, cs.getIndex());
  325. // Look at the low level xml elements
  326. assertEquals(2, cs.getCoreXf().getFillId());
  327. assertEquals(0, cs.getCoreXf().getXfId());
  328. assertTrue(cs.getCoreXf().getApplyFill());
  329. XSSFCellFill fg = wb.getStylesSource().getFillAt(2);
  330. assertNotNull(fg.getFillForegroundColor());
  331. assertEquals(0, fg.getFillForegroundColor().getIndexed());
  332. assertEquals(0.0, fg.getFillForegroundColor().getTint(), 0);
  333. assertEquals("FFFF0000", fg.getFillForegroundColor().getARGBHex());
  334. assertNotNull(fg.getFillBackgroundColor());
  335. assertEquals(64, fg.getFillBackgroundColor().getIndexed());
  336. // Now look higher up
  337. assertNotNull(cs.getFillForegroundXSSFColor());
  338. assertEquals(0, cs.getFillForegroundColor());
  339. assertEquals("FFFF0000", cs.getFillForegroundXSSFColor().getARGBHex());
  340. assertEquals("FFFF0000", cs.getFillForegroundColorColor().getARGBHex());
  341. assertEquals(64, cs.getFillBackgroundColor());
  342. assertNull(cs.getFillBackgroundXSSFColor().getARGBHex());
  343. assertNull(cs.getFillBackgroundColorColor().getARGBHex());
  344. }
  345. }
  346. /**
  347. * Ensure General and @ format are working properly
  348. * for integers
  349. */
  350. @Test
  351. public void bug47490() throws IOException {
  352. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("GeneralFormatTests.xlsx")) {
  353. Sheet s = wb.getSheetAt(1);
  354. Row r;
  355. DataFormatter df = new DataFormatter();
  356. r = s.getRow(1);
  357. assertEquals(1.0, r.getCell(2).getNumericCellValue(), 0);
  358. assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString());
  359. assertEquals("1", df.formatCellValue(r.getCell(2)));
  360. assertEquals("1", df.formatRawCellContents(1.0, -1, "@"));
  361. assertEquals("1", df.formatRawCellContents(1.0, -1, "General"));
  362. r = s.getRow(2);
  363. assertEquals(12.0, r.getCell(2).getNumericCellValue(), 0);
  364. assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString());
  365. assertEquals("12", df.formatCellValue(r.getCell(2)));
  366. assertEquals("12", df.formatRawCellContents(12.0, -1, "@"));
  367. assertEquals("12", df.formatRawCellContents(12.0, -1, "General"));
  368. r = s.getRow(3);
  369. assertEquals(123.0, r.getCell(2).getNumericCellValue(), 0);
  370. assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString());
  371. assertEquals("123", df.formatCellValue(r.getCell(2)));
  372. assertEquals("123", df.formatRawCellContents(123.0, -1, "@"));
  373. assertEquals("123", df.formatRawCellContents(123.0, -1, "General"));
  374. }
  375. }
  376. /**
  377. * A problem file from a non-standard source (a scientific instrument that saves its
  378. * output as an .xlsx file) that have two issues:
  379. * 1. The Content Type part name is lower-case: [content_types].xml
  380. * 2. The file appears to use backslashes as path separators
  381. * <p>
  382. * The OPC spec tolerates both of these peculiarities, so does POI
  383. */
  384. @Test
  385. public void bug49609() throws IOException {
  386. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49609.xlsx")) {
  387. assertEquals("FAM", wb.getSheetName(0));
  388. assertEquals("Cycle", wb.getSheetAt(0).getRow(0).getCell(1).getStringCellValue());
  389. }
  390. }
  391. @Test
  392. public void bug49783() throws IOException {
  393. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49783.xlsx")) {
  394. Sheet sheet = wb.getSheetAt(0);
  395. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  396. Cell cell;
  397. cell = sheet.getRow(0).getCell(0);
  398. assertEquals("#REF!*#REF!", cell.getCellFormula());
  399. assertEquals(CellType.ERROR, evaluator.evaluateInCell(cell).getCellType());
  400. assertEquals("#REF!", FormulaError.forInt(cell.getErrorCellValue()).getString());
  401. Name nm1 = wb.getName("sale_1");
  402. assertNotNull("name sale_1 should be present", nm1);
  403. assertEquals("Sheet1!#REF!", nm1.getRefersToFormula());
  404. Name nm2 = wb.getName("sale_2");
  405. assertNotNull("name sale_2 should be present", nm2);
  406. assertEquals("Sheet1!#REF!", nm2.getRefersToFormula());
  407. cell = sheet.getRow(1).getCell(0);
  408. assertEquals("sale_1*sale_2", cell.getCellFormula());
  409. assertEquals(CellType.ERROR, evaluator.evaluateInCell(cell).getCellType());
  410. assertEquals("#REF!", FormulaError.forInt(cell.getErrorCellValue()).getString());
  411. }
  412. }
  413. /**
  414. * Creating a rich string of "hello world" and applying
  415. * a font to characters 1-5 means we have two strings,
  416. * "hello" and " world". As such, we need to apply
  417. * preserve spaces to the 2nd bit, lest we end up
  418. * with something like "helloworld" !
  419. */
  420. @Test
  421. public void bug49941() throws IOException {
  422. XSSFWorkbook wb1 = new XSSFWorkbook();
  423. XSSFSheet s = wb1.createSheet();
  424. XSSFRow r = s.createRow(0);
  425. XSSFCell c = r.createCell(0);
  426. // First without fonts
  427. c.setCellValue(
  428. new XSSFRichTextString(" with spaces ")
  429. );
  430. assertEquals(" with spaces ", c.getRichStringCellValue().toString());
  431. assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray());
  432. assertTrue(c.getRichStringCellValue().getCTRst().isSetT());
  433. // Should have the preserve set
  434. assertEquals(
  435. 1,
  436. c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength()
  437. );
  438. assertEquals(
  439. "preserve",
  440. c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().item(0).getNodeValue()
  441. );
  442. // Save and check
  443. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  444. wb1.close();
  445. s = wb2.getSheetAt(0);
  446. r = s.getRow(0);
  447. c = r.getCell(0);
  448. assertEquals(" with spaces ", c.getRichStringCellValue().toString());
  449. assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray());
  450. assertTrue(c.getRichStringCellValue().getCTRst().isSetT());
  451. // Change the string
  452. c.setCellValue(
  453. new XSSFRichTextString("hello world")
  454. );
  455. assertEquals("hello world", c.getRichStringCellValue().toString());
  456. // Won't have preserve
  457. assertEquals(
  458. 0,
  459. c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength()
  460. );
  461. // Apply a font
  462. XSSFFont f = wb2.createFont();
  463. f.setBold(true);
  464. c.getRichStringCellValue().applyFont(0, 5, f);
  465. assertEquals("hello world", c.getRichStringCellValue().toString());
  466. // Does need preserving on the 2nd part
  467. assertEquals(2, c.getRichStringCellValue().getCTRst().sizeOfRArray());
  468. assertEquals(
  469. 0,
  470. c.getRichStringCellValue().getCTRst().getRArray(0).xgetT().getDomNode().getAttributes().getLength()
  471. );
  472. assertEquals(
  473. 1,
  474. c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().getLength()
  475. );
  476. assertEquals(
  477. "preserve",
  478. c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().item(0).getNodeValue()
  479. );
  480. // Save and check
  481. XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
  482. wb2.close();
  483. s = wb3.getSheetAt(0);
  484. r = s.getRow(0);
  485. c = r.getCell(0);
  486. assertEquals("hello world", c.getRichStringCellValue().toString());
  487. wb3.close();
  488. }
  489. /**
  490. * Repeatedly writing the same file which has styles
  491. */
  492. @Test
  493. public void bug49940() throws IOException {
  494. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("styles.xlsx")) {
  495. assertEquals(3, wb.getNumberOfSheets());
  496. assertEquals(10, wb.getStylesSource().getNumCellStyles());
  497. ByteArrayOutputStream b1 = new ByteArrayOutputStream();
  498. ByteArrayOutputStream b2 = new ByteArrayOutputStream();
  499. ByteArrayOutputStream b3 = new ByteArrayOutputStream();
  500. wb.write(b1);
  501. wb.write(b2);
  502. wb.write(b3);
  503. for (byte[] data : new byte[][]{
  504. b1.toByteArray(), b2.toByteArray(), b3.toByteArray()
  505. }) {
  506. ByteArrayInputStream bais = new ByteArrayInputStream(data);
  507. XSSFWorkbook wb2 = new XSSFWorkbook(bais);
  508. assertEquals(3, wb2.getNumberOfSheets());
  509. assertEquals(10, wb2.getStylesSource().getNumCellStyles());
  510. wb2.close();
  511. }
  512. }
  513. }
  514. /**
  515. * Various ways of removing a cell formula should all zap the calcChain
  516. * entry.
  517. */
  518. @Test
  519. public void bug49966() throws IOException {
  520. try (XSSFWorkbook wb1 = XSSFTestDataSamples
  521. .openSampleWorkbook("shared_formulas.xlsx")) {
  522. XSSFSheet sheet = wb1.getSheetAt(0);
  523. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  524. // CalcChain has lots of entries
  525. CalculationChain cc = wb1.getCalculationChain();
  526. assertEquals("A2", cc.getCTCalcChain().getCArray(0).getR());
  527. assertEquals("A3", cc.getCTCalcChain().getCArray(1).getR());
  528. assertEquals("A4", cc.getCTCalcChain().getCArray(2).getR());
  529. assertEquals("A5", cc.getCTCalcChain().getCArray(3).getR());
  530. assertEquals("A6", cc.getCTCalcChain().getCArray(4).getR());
  531. assertEquals("A7", cc.getCTCalcChain().getCArray(5).getR());
  532. assertEquals("A8", cc.getCTCalcChain().getCArray(6).getR());
  533. assertEquals(40, cc.getCTCalcChain().sizeOfCArray());
  534. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  535. // Try various ways of changing the formulas
  536. // If it stays a formula, chain entry should remain
  537. // Otherwise should go
  538. sheet.getRow(1).getCell(0).setCellFormula("A1"); // stay
  539. sheet.getRow(2).getCell(0).setCellFormula(null); // go
  540. sheet.getRow(3).getCell(0).setCellFormula("14"); // stay
  541. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  542. sheet.getRow(4).getCell(0).setBlank(); // go
  543. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  544. validateCells(sheet);
  545. sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go
  546. validateCells(sheet);
  547. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  548. sheet.getRow(6).getCell(0).setBlank(); // go
  549. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  550. sheet.getRow(7).getCell(0).setCellValue((String) null); // go
  551. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  552. // Save and check
  553. try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) {
  554. wb1.close();
  555. assertEquals(35, cc.getCTCalcChain().sizeOfCArray());
  556. cc = wb2.getCalculationChain();
  557. assertEquals("A2", cc.getCTCalcChain().getCArray(0).getR());
  558. assertEquals("A4", cc.getCTCalcChain().getCArray(1).getR());
  559. assertEquals("A9", cc.getCTCalcChain().getCArray(2).getR());
  560. }
  561. }
  562. }
  563. @Test
  564. public void bug49966Row() throws IOException {
  565. try (XSSFWorkbook wb = XSSFTestDataSamples
  566. .openSampleWorkbook("shared_formulas.xlsx")) {
  567. XSSFSheet sheet = wb.getSheetAt(0);
  568. validateCells(sheet);
  569. sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go
  570. validateCells(sheet);
  571. }
  572. }
  573. private void validateCells(XSSFSheet sheet) {
  574. for (Row row : sheet) {
  575. // trigger handling
  576. ((XSSFRow) row).onDocumentWrite();
  577. }
  578. }
  579. @Test
  580. public void bug49156() throws IOException {
  581. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49156.xlsx")) {
  582. FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
  583. Sheet sheet = wb.getSheetAt(0);
  584. for (Row row : sheet) {
  585. for (Cell cell : row) {
  586. if (cell.getCellType() == CellType.FORMULA) {
  587. formulaEvaluator.evaluateInCell(cell); // caused NPE on some cells
  588. }
  589. }
  590. }
  591. }
  592. }
  593. /**
  594. * Newlines are valid characters in a formula
  595. */
  596. @Test
  597. public void bug50440And51875() throws IOException {
  598. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("NewlineInFormulas.xlsx")) {
  599. Sheet s = wb.getSheetAt(0);
  600. Cell c = s.getRow(0).getCell(0);
  601. assertEquals("SUM(\n1,2\n)", c.getCellFormula());
  602. assertEquals(3.0, c.getNumericCellValue(), 0);
  603. FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
  604. formulaEvaluator.evaluateFormulaCell(c);
  605. assertEquals("SUM(\n1,2\n)", c.getCellFormula());
  606. assertEquals(3.0, c.getNumericCellValue(), 0);
  607. // For 51875
  608. Cell b3 = s.getRow(2).getCell(1);
  609. formulaEvaluator.evaluateFormulaCell(b3);
  610. assertEquals("B1+B2", b3.getCellFormula()); // The newline is lost for shared formulas
  611. assertEquals(3.0, b3.getNumericCellValue(), 0);
  612. }
  613. }
  614. /**
  615. * Moving a cell comment from one cell to another
  616. */
  617. @Test
  618. public void bug50795() throws IOException {
  619. XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("50795.xlsx");
  620. XSSFSheet sheet = wb1.getSheetAt(0);
  621. XSSFRow row = sheet.getRow(0);
  622. XSSFCell cellWith = row.getCell(0);
  623. XSSFCell cellWithoutComment = row.getCell(1);
  624. assertNotNull(cellWith.getCellComment());
  625. assertNull(cellWithoutComment.getCellComment());
  626. String exp = "\u0410\u0432\u0442\u043e\u0440:\ncomment";
  627. XSSFComment comment = cellWith.getCellComment();
  628. assertEquals(exp, comment.getString().getString());
  629. // Check we can write it out and read it back as-is
  630. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  631. wb1.close();
  632. sheet = wb2.getSheetAt(0);
  633. row = sheet.getRow(0);
  634. cellWith = row.getCell(0);
  635. cellWithoutComment = row.getCell(1);
  636. // Double check things are as expected
  637. assertNotNull(cellWith.getCellComment());
  638. assertNull(cellWithoutComment.getCellComment());
  639. comment = cellWith.getCellComment();
  640. assertEquals(exp, comment.getString().getString());
  641. // Move the comment
  642. cellWithoutComment.setCellComment(comment);
  643. // Write out and re-check
  644. XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
  645. wb2.close();
  646. sheet = wb3.getSheetAt(0);
  647. row = sheet.getRow(0);
  648. // Ensure it swapped over
  649. cellWith = row.getCell(0);
  650. cellWithoutComment = row.getCell(1);
  651. assertNull(cellWith.getCellComment());
  652. assertNotNull(cellWithoutComment.getCellComment());
  653. comment = cellWithoutComment.getCellComment();
  654. assertEquals(exp, comment.getString().getString());
  655. wb3.close();
  656. }
  657. /**
  658. * When the cell background colour is set with one of the first
  659. * two columns of the theme colour palette, the colours are
  660. * shades of white or black.
  661. * For those cases, ensure we don't break on reading the colour
  662. */
  663. @Test
  664. public void bug50299() throws IOException {
  665. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50299.xlsx")) {
  666. // Check all the colours
  667. for (int sn = 0; sn < wb.getNumberOfSheets(); sn++) {
  668. Sheet s = wb.getSheetAt(sn);
  669. for (Row r : s) {
  670. for (Cell c : r) {
  671. CellStyle cs = c.getCellStyle();
  672. if (cs != null) {
  673. cs.getFillForegroundColor();
  674. }
  675. }
  676. }
  677. }
  678. // Check one bit in detail
  679. // Check that we get back foreground=0 for the theme colours,
  680. // and background=64 for the auto colouring
  681. Sheet s = wb.getSheetAt(0);
  682. assertEquals(0, s.getRow(0).getCell(8).getCellStyle().getFillForegroundColor());
  683. assertEquals(64, s.getRow(0).getCell(8).getCellStyle().getFillBackgroundColor());
  684. assertEquals(0, s.getRow(1).getCell(8).getCellStyle().getFillForegroundColor());
  685. assertEquals(64, s.getRow(1).getCell(8).getCellStyle().getFillBackgroundColor());
  686. }
  687. }
  688. /**
  689. * Excel .xls style indexed colours in a .xlsx file
  690. */
  691. @Test
  692. public void bug50786() throws IOException {
  693. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50786-indexed_colours.xlsx")) {
  694. XSSFSheet s = wb.getSheetAt(0);
  695. XSSFRow r = s.getRow(2);
  696. // Check we have the right cell
  697. XSSFCell c = r.getCell(1);
  698. assertEquals("test\u00a0", c.getRichStringCellValue().getString());
  699. // It should be light green
  700. XSSFCellStyle cs = c.getCellStyle();
  701. assertEquals(42, cs.getFillForegroundColor());
  702. assertEquals(42, cs.getFillForegroundColorColor().getIndexed());
  703. assertNotNull(cs.getFillForegroundColorColor().getRGB());
  704. assertEquals("FFCCFFCC", cs.getFillForegroundColorColor().getARGBHex());
  705. }
  706. }
  707. /**
  708. * If the border colours are set with themes, then we
  709. * should still be able to get colours
  710. */
  711. @Test
  712. public void bug50846() throws IOException {
  713. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50846-border_colours.xlsx")) {
  714. XSSFSheet sheet = wb.getSheetAt(0);
  715. XSSFRow row = sheet.getRow(0);
  716. // Border from a theme, brown
  717. XSSFCell cellT = row.getCell(0);
  718. XSSFCellStyle styleT = cellT.getCellStyle();
  719. XSSFColor colorT = styleT.getBottomBorderXSSFColor();
  720. assertEquals(5, colorT.getTheme());
  721. assertEquals("FFC0504D", colorT.getARGBHex());
  722. // Border from a style direct, red
  723. XSSFCell cellS = row.getCell(1);
  724. XSSFCellStyle styleS = cellS.getCellStyle();
  725. XSSFColor colorS = styleS.getBottomBorderXSSFColor();
  726. assertEquals(0, colorS.getTheme());
  727. assertEquals("FFFF0000", colorS.getARGBHex());
  728. }
  729. }
  730. /**
  731. * Fonts where their colours come from the theme rather
  732. * then being set explicitly still should allow the
  733. * fetching of the RGB.
  734. */
  735. @Test
  736. public void bug50784() throws IOException {
  737. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50784-font_theme_colours.xlsx")) {
  738. XSSFSheet s = wb.getSheetAt(0);
  739. XSSFRow r = s.getRow(0);
  740. // Column 1 has a font with regular colours
  741. XSSFCell cr = r.getCell(1);
  742. XSSFFont fr = wb.getFontAt(cr.getCellStyle().getFontIndexAsInt());
  743. XSSFColor colr = fr.getXSSFColor();
  744. // No theme, has colours
  745. assertEquals(0, colr.getTheme());
  746. assertNotNull(colr.getRGB());
  747. // Column 0 has a font with colours from a theme
  748. XSSFCell ct = r.getCell(0);
  749. XSSFFont ft = wb.getFontAt(ct.getCellStyle().getFontIndexAsInt());
  750. XSSFColor colt = ft.getXSSFColor();
  751. // Has a theme, which has the colours on it
  752. assertEquals(9, colt.getTheme());
  753. XSSFColor themeC = wb.getTheme().getThemeColor(colt.getTheme());
  754. assertNotNull(themeC.getRGB());
  755. assertNotNull(colt.getRGB());
  756. assertEquals(themeC.getARGBHex(), colt.getARGBHex()); // The same colour
  757. }
  758. }
  759. /**
  760. * New lines were being eaten when setting a font on
  761. * a rich text string
  762. */
  763. @Test
  764. public void bug48877() throws IOException {
  765. String text = "Use \n with word wrap on to create a new line.\n" +
  766. "This line finishes with two trailing spaces. ";
  767. XSSFWorkbook wb1 = new XSSFWorkbook();
  768. XSSFSheet sheet = wb1.createSheet();
  769. Font font1 = wb1.createFont();
  770. font1.setColor((short) 20);
  771. Font font2 = wb1.createFont();
  772. font2.setColor(Font.COLOR_RED);
  773. Font font3 = wb1.getFontAt(0);
  774. XSSFRow row = sheet.createRow(2);
  775. XSSFCell cell = row.createCell(2);
  776. XSSFRichTextString richTextString =
  777. wb1.getCreationHelper().createRichTextString(text);
  778. // Check the text has the newline
  779. assertEquals(text, richTextString.getString());
  780. // Apply the font
  781. richTextString.applyFont(font3);
  782. richTextString.applyFont(0, 3, font1);
  783. cell.setCellValue(richTextString);
  784. // To enable newlines you need set a cell styles with wrap=true
  785. CellStyle cs = wb1.createCellStyle();
  786. cs.setWrapText(true);
  787. cell.setCellStyle(cs);
  788. // Check the text has the
  789. assertEquals(text, cell.getStringCellValue());
  790. // Save the file and re-read it
  791. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  792. wb1.close();
  793. sheet = wb2.getSheetAt(0);
  794. row = sheet.getRow(2);
  795. cell = row.getCell(2);
  796. assertEquals(text, cell.getStringCellValue());
  797. // Now add a 2nd, and check again
  798. int fontAt = text.indexOf('\n', 6);
  799. cell.getRichStringCellValue().applyFont(10, fontAt + 1, font2);
  800. assertEquals(text, cell.getStringCellValue());
  801. assertEquals(4, cell.getRichStringCellValue().numFormattingRuns());
  802. assertEquals("Use", cell.getRichStringCellValue().getCTRst().getRArray(0).getT());
  803. String r3 = cell.getRichStringCellValue().getCTRst().getRArray(2).getT();
  804. assertEquals("line.\n", r3.substring(r3.length() - 6));
  805. // Save and re-check
  806. XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
  807. wb2.close();
  808. sheet = wb3.getSheetAt(0);
  809. row = sheet.getRow(2);
  810. cell = row.getCell(2);
  811. assertEquals(text, cell.getStringCellValue());
  812. wb3.close();
  813. // FileOutputStream out = new FileOutputStream("/tmp/test48877.xlsx");
  814. // wb.write(out);
  815. // out.close();
  816. }
  817. /**
  818. * Adding sheets when one has a table, then re-ordering
  819. */
  820. @Test
  821. public void bug50867() throws IOException {
  822. XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("50867_with_table.xlsx");
  823. assertEquals(3, wb1.getNumberOfSheets());
  824. XSSFSheet s1 = wb1.getSheetAt(0);
  825. XSSFSheet s2 = wb1.getSheetAt(1);
  826. XSSFSheet s3 = wb1.getSheetAt(2);
  827. assertEquals(1, s1.getTables().size());
  828. assertEquals(0, s2.getTables().size());
  829. assertEquals(0, s3.getTables().size());
  830. XSSFTable t = s1.getTables().get(0);
  831. assertEquals("Tabella1", t.getName());
  832. assertEquals("Tabella1", t.getDisplayName());
  833. assertEquals("A1:C3", t.getCTTable().getRef());
  834. // Add a sheet and re-order
  835. XSSFSheet s4 = wb1.createSheet("NewSheet");
  836. wb1.setSheetOrder(s4.getSheetName(), 0);
  837. // Check on tables
  838. assertEquals(1, s1.getTables().size());
  839. assertEquals(0, s2.getTables().size());
  840. assertEquals(0, s3.getTables().size());
  841. assertEquals(0, s4.getTables().size());
  842. // Refetch to get the new order
  843. s1 = wb1.getSheetAt(0);
  844. s2 = wb1.getSheetAt(1);
  845. s3 = wb1.getSheetAt(2);
  846. s4 = wb1.getSheetAt(3);
  847. assertEquals(0, s1.getTables().size());
  848. assertEquals(1, s2.getTables().size());
  849. assertEquals(0, s3.getTables().size());
  850. assertEquals(0, s4.getTables().size());
  851. // Save and re-load
  852. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  853. wb1.close();
  854. s1 = wb2.getSheetAt(0);
  855. s2 = wb2.getSheetAt(1);
  856. s3 = wb2.getSheetAt(2);
  857. s4 = wb2.getSheetAt(3);
  858. assertEquals(0, s1.getTables().size());
  859. assertEquals(1, s2.getTables().size());
  860. assertEquals(0, s3.getTables().size());
  861. assertEquals(0, s4.getTables().size());
  862. t = s2.getTables().get(0);
  863. assertEquals("Tabella1", t.getName());
  864. assertEquals("Tabella1", t.getDisplayName());
  865. assertEquals("A1:C3", t.getCTTable().getRef());
  866. // Add some more tables, and check
  867. t = s2.createTable(null);
  868. t.setName("New 2");
  869. t.setDisplayName("New 2");
  870. t = s3.createTable(null);
  871. t.setName("New 3");
  872. t.setDisplayName("New 3");
  873. XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
  874. wb2.close();
  875. s1 = wb3.getSheetAt(0);
  876. s2 = wb3.getSheetAt(1);
  877. s3 = wb3.getSheetAt(2);
  878. s4 = wb3.getSheetAt(3);
  879. assertEquals(0, s1.getTables().size());
  880. assertEquals(2, s2.getTables().size());
  881. assertEquals(1, s3.getTables().size());
  882. assertEquals(0, s4.getTables().size());
  883. t = s2.getTables().get(0);
  884. assertEquals("Tabella1", t.getName());
  885. assertEquals("Tabella1", t.getDisplayName());
  886. assertEquals("A1:C3", t.getCTTable().getRef());
  887. t = s2.getTables().get(1);
  888. assertEquals("New 2", t.getName());
  889. assertEquals("New 2", t.getDisplayName());
  890. t = s3.getTables().get(0);
  891. assertEquals("New 3", t.getName());
  892. assertEquals("New 3", t.getDisplayName());
  893. // Check the relationships
  894. assertEquals(0, s1.getRelations().size());
  895. assertEquals(3, s2.getRelations().size());
  896. assertEquals(1, s3.getRelations().size());
  897. assertEquals(0, s4.getRelations().size());
  898. assertEquals(
  899. XSSFRelation.PRINTER_SETTINGS.getContentType(),
  900. s2.getRelations().get(0).getPackagePart().getContentType()
  901. );
  902. assertEquals(
  903. XSSFRelation.TABLE.getContentType(),
  904. s2.getRelations().get(1).getPackagePart().getContentType()
  905. );
  906. assertEquals(
  907. XSSFRelation.TABLE.getContentType(),
  908. s2.getRelations().get(2).getPackagePart().getContentType()
  909. );
  910. assertEquals(
  911. XSSFRelation.TABLE.getContentType(),
  912. s3.getRelations().get(0).getPackagePart().getContentType()
  913. );
  914. assertEquals(
  915. "/xl/tables/table3.xml",
  916. s3.getRelations().get(0).getPackagePart().getPartName().toString()
  917. );
  918. wb3.close();
  919. }
  920. /**
  921. * Setting repeating rows and columns shouldn't break
  922. * any print settings that were there before
  923. */
  924. @Test
  925. public void bug49253() throws IOException {
  926. XSSFWorkbook wb1 = new XSSFWorkbook();
  927. XSSFWorkbook wb2 = new XSSFWorkbook();
  928. CellRangeAddress cra = CellRangeAddress.valueOf("C2:D3");
  929. // No print settings before repeating
  930. XSSFSheet s1 = wb1.createSheet();
  931. assertFalse(s1.getCTWorksheet().isSetPageSetup());
  932. assertTrue(s1.getCTWorksheet().isSetPageMargins());
  933. s1.setRepeatingColumns(cra);
  934. s1.setRepeatingRows(cra);
  935. assertTrue(s1.getCTWorksheet().isSetPageSetup());
  936. assertTrue(s1.getCTWorksheet().isSetPageMargins());
  937. PrintSetup ps1 = s1.getPrintSetup();
  938. assertFalse(ps1.getValidSettings());
  939. assertFalse(ps1.getLandscape());
  940. // Had valid print settings before repeating
  941. XSSFSheet s2 = wb2.createSheet();
  942. PrintSetup ps2 = s2.getPrintSetup();
  943. assertTrue(s2.getCTWorksheet().isSetPageSetup());
  944. assertTrue(s2.getCTWorksheet().isSetPageMargins());
  945. ps2.setLandscape(false);
  946. assertTrue(ps2.getValidSettings());
  947. assertFalse(ps2.getLandscape());
  948. s2.setRepeatingColumns(cra);
  949. s2.setRepeatingRows(cra);
  950. ps2 = s2.getPrintSetup();
  951. assertTrue(s2.getCTWorksheet().isSetPageSetup());
  952. assertTrue(s2.getCTWorksheet().isSetPageMargins());
  953. assertTrue(ps2.getValidSettings());
  954. assertFalse(ps2.getLandscape());
  955. wb1.close();
  956. wb2.close();
  957. }
  958. /**
  959. * Default Column style
  960. */
  961. @Test
  962. public void bug51037() throws IOException {
  963. XSSFWorkbook wb = new XSSFWorkbook();
  964. XSSFSheet s = wb.createSheet();
  965. CellStyle defaultStyle = wb.getCellStyleAt((short) 0);
  966. assertEquals(0, defaultStyle.getIndex());
  967. CellStyle blueStyle = wb.createCellStyle();
  968. blueStyle.setFillForegroundColor(IndexedColors.AQUA.getIndex());
  969. blueStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  970. assertEquals(1, blueStyle.getIndex());
  971. CellStyle pinkStyle = wb.createCellStyle();
  972. pinkStyle.setFillForegroundColor(IndexedColors.PINK.getIndex());
  973. pinkStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  974. assertEquals(2, pinkStyle.getIndex());
  975. // Starts empty
  976. assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
  977. CTCols cols = s.getCTWorksheet().getColsArray(0);
  978. assertEquals(0, cols.sizeOfColArray());
  979. // Add some rows and columns
  980. XSSFRow r1 = s.createRow(0);
  981. XSSFRow r2 = s.createRow(1);
  982. r1.createCell(0);
  983. r1.createCell(2);
  984. r2.createCell(0);
  985. r2.createCell(3);
  986. // Check no style is there
  987. assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
  988. assertEquals(0, cols.sizeOfColArray());
  989. assertEquals(defaultStyle, s.getColumnStyle(0));
  990. assertEquals(defaultStyle, s.getColumnStyle(2));
  991. assertEquals(defaultStyle, s.getColumnStyle(3));
  992. // Apply the styles
  993. s.setDefaultColumnStyle(0, pinkStyle);
  994. s.setDefaultColumnStyle(3, blueStyle);
  995. // Check
  996. assertEquals(pinkStyle, s.getColumnStyle(0));
  997. assertEquals(defaultStyle, s.getColumnStyle(2));
  998. assertEquals(blueStyle, s.getColumnStyle(3));
  999. assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
  1000. assertEquals(2, cols.sizeOfColArray());
  1001. assertEquals(1, cols.getColArray(0).getMin());
  1002. assertEquals(1, cols.getColArray(0).getMax());
  1003. assertEquals(pinkStyle.getIndex(), cols.getColArray(0).getStyle());
  1004. assertEquals(4, cols.getColArray(1).getMin());
  1005. assertEquals(4, cols.getColArray(1).getMax());
  1006. assertEquals(blueStyle.getIndex(), cols.getColArray(1).getStyle());
  1007. // Save, re-load and re-check
  1008. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1009. wb.close();
  1010. s = wbBack.getSheetAt(0);
  1011. defaultStyle = wbBack.getCellStyleAt(defaultStyle.getIndex());
  1012. blueStyle = wbBack.getCellStyleAt(blueStyle.getIndex());
  1013. pinkStyle = wbBack.getCellStyleAt(pinkStyle.getIndex());
  1014. assertEquals(pinkStyle, s.getColumnStyle(0));
  1015. assertEquals(defaultStyle, s.getColumnStyle(2));
  1016. assertEquals(blueStyle, s.getColumnStyle(3));
  1017. wbBack.close();
  1018. }
  1019. /**
  1020. * Repeatedly writing a file.
  1021. * Something with the SharedStringsTable currently breaks...
  1022. */
  1023. @Test
  1024. public void bug46662() throws IOException {
  1025. // New file
  1026. XSSFWorkbook wb1 = new XSSFWorkbook();
  1027. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  1028. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  1029. XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
  1030. wb1.close();
  1031. // Simple file
  1032. XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx");
  1033. XSSFTestDataSamples.writeOutAndReadBack(wb2).close();
  1034. XSSFTestDataSamples.writeOutAndReadBack(wb2).close();
  1035. XSSFTestDataSamples.writeOutAndReadBack(wb2).close();
  1036. wb2.close();
  1037. // Complex file
  1038. // TODO
  1039. }
  1040. /**
  1041. * Colours and styles when the list has gaps in it
  1042. */
  1043. @Test
  1044. public void bug51222() throws IOException {
  1045. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51222.xlsx")) {
  1046. XSSFSheet s = wb.getSheetAt(0);
  1047. XSSFCell cA4_EEECE1 = s.getRow(3).getCell(0);
  1048. XSSFCell cA5_1F497D = s.getRow(4).getCell(0);
  1049. // Check the text
  1050. assertEquals("A4", cA4_EEECE1.getRichStringCellValue().getString());
  1051. assertEquals("A5", cA5_1F497D.getRichStringCellValue().getString());
  1052. // Check the styles assigned to them
  1053. assertEquals(4, cA4_EEECE1.getCTCell().getS());
  1054. assertEquals(5, cA5_1F497D.getCTCell().getS());
  1055. // Check we look up the correct style
  1056. assertEquals(4, cA4_EEECE1.getCellStyle().getIndex());
  1057. assertEquals(5, cA5_1F497D.getCellStyle().getIndex());
  1058. // Check the fills on them at the low level
  1059. assertEquals(5, cA4_EEECE1.getCellStyle().getCoreXf().getFillId());
  1060. assertEquals(6, cA5_1F497D.getCellStyle().getCoreXf().getFillId());
  1061. // These should reference themes 2 and 3
  1062. assertEquals(2, wb.getStylesSource().getFillAt(5).getCTFill().getPatternFill().getFgColor().getTheme());
  1063. assertEquals(3, wb.getStylesSource().getFillAt(6).getCTFill().getPatternFill().getFgColor().getTheme());
  1064. // Ensure we get the right colours for these themes
  1065. // TODO fix
  1066. // assertEquals("FFEEECE1", wb.getTheme().getThemeColor(2).getARGBHex());
  1067. // assertEquals("FF1F497D", wb.getTheme().getThemeColor(3).getARGBHex());
  1068. // Finally check the colours on the styles
  1069. // TODO fix
  1070. // assertEquals("FFEEECE1", cA4_EEECE1.getCellStyle().getFillForegroundXSSFColor().getARGBHex());
  1071. // assertEquals("FF1F497D", cA5_1F497D.getCellStyle().getFillForegroundXSSFColor().getARGBHex());
  1072. }
  1073. }
  1074. @Test
  1075. public void bug51470() throws IOException {
  1076. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51470.xlsx")) {
  1077. XSSFSheet sh0 = wb.getSheetAt(0);
  1078. XSSFSheet sh1 = wb.cloneSheet(0);
  1079. List<RelationPart> rels0 = sh0.getRelationParts();
  1080. List<RelationPart> rels1 = sh1.getRelationParts();
  1081. assertEquals(1, rels0.size());
  1082. assertEquals(1, rels1.size());
  1083. PackageRelationship pr0 = rels0.get(0).getRelationship();
  1084. PackageRelationship pr1 = rels1.get(0).getRelationship();
  1085. assertEquals(pr0.getTargetMode(), pr1.getTargetMode());
  1086. assertEquals(pr0.getTargetURI(), pr1.getTargetURI());
  1087. POIXMLDocumentPart doc0 = rels0.get(0).getDocumentPart();
  1088. POIXMLDocumentPart doc1 = rels1.get(0).getDocumentPart();
  1089. assertEquals(doc0, doc1);
  1090. }
  1091. }
  1092. /**
  1093. * Add comments to Sheet 1, when Sheet 2 already has
  1094. * comments (so /xl/comments1.xml is taken)
  1095. */
  1096. @Test
  1097. public void bug51850() throws IOException {
  1098. XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("51850.xlsx");
  1099. XSSFSheet sh1 = wb1.getSheetAt(0);
  1100. XSSFSheet sh2 = wb1.getSheetAt(1);
  1101. // Sheet 2 has comments
  1102. assertNotNull(sh2.getCommentsTable(false));
  1103. assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments());
  1104. // Sheet 1 doesn't (yet)
  1105. assertNull(sh1.getCommentsTable(false));
  1106. // Try to add comments to Sheet 1
  1107. CreationHelper factory = wb1.getCreationHelper();
  1108. Drawing<?> drawing = sh1.createDrawingPatriarch();
  1109. ClientAnchor anchor = factory.createClientAnchor();
  1110. anchor.setCol1(0);
  1111. anchor.setCol2(4);
  1112. anchor.setRow1(0);
  1113. anchor.setRow2(1);
  1114. Comment comment1 = drawing.createCellComment(anchor);
  1115. comment1.setString(
  1116. factory.createRichTextString("I like this cell. It's my favourite."));
  1117. comment1.setAuthor("Bob T. Fish");
  1118. anchor = factory.createClientAnchor();
  1119. anchor.setCol1(0);
  1120. anchor.setCol2(4);
  1121. anchor.setRow1(1);
  1122. anchor.setRow2(1);
  1123. Comment comment2 = drawing.createCellComment(anchor);
  1124. comment2.setString(
  1125. factory.createRichTextString("This is much less fun..."));
  1126. comment2.setAuthor("Bob T. Fish");
  1127. Cell c1 = sh1.getRow(0).createCell(4);
  1128. c1.setCellValue(2.3);
  1129. c1.setCellComment(comment1);
  1130. Cell c2 = sh1.getRow(0).createCell(5);
  1131. c2.setCellValue(2.1);
  1132. c2.setCellComment(comment2);
  1133. // Save and re-load
  1134. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  1135. wb1.close();
  1136. sh1 = wb2.getSheetAt(0);
  1137. sh2 = wb2.getSheetAt(1);
  1138. // Check the comments
  1139. assertNotNull(sh2.getCommentsTable(false));
  1140. assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments());
  1141. assertNotNull(sh1.getCommentsTable(false));
  1142. assertEquals(2, sh1.getCommentsTable(false).getNumberOfComments());
  1143. wb2.close();
  1144. }
  1145. /**
  1146. * Sheet names with a , in them
  1147. */
  1148. @Test
  1149. public void bug51963() throws IOException {
  1150. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51963.xlsx")) {
  1151. Sheet sheet = wb.getSheetAt(0);
  1152. assertEquals("Abc,1", sheet.getSheetName());
  1153. Name name = wb.getName("Intekon.ProdCodes");
  1154. assertEquals("'Abc,1'!$A$1:$A$2", name.getRefersToFormula());
  1155. AreaReference ref = wb.getCreationHelper().createAreaReference(name.getRefersToFormula());
  1156. assertEquals(0, ref.getFirstCell().getRow());
  1157. assertEquals(0, ref.getFirstCell().getCol());
  1158. assertEquals(1, ref.getLastCell().getRow());
  1159. assertEquals(0, ref.getLastCell().getCol());
  1160. }
  1161. }
  1162. /**
  1163. * Sum across multiple workbooks
  1164. * eg =SUM($Sheet1.C1:$Sheet4.C1)
  1165. */
  1166. @Test
  1167. public void bug48703() throws IOException {
  1168. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48703.xlsx")) {
  1169. XSSFSheet sheet = wb.getSheetAt(0);
  1170. // Contains two forms, one with a range and one a list
  1171. XSSFRow r1 = sheet.getRow(0);
  1172. XSSFRow r2 = sheet.getRow(1);
  1173. XSSFCell c1 = r1.getCell(1);
  1174. XSSFCell c2 = r2.getCell(1);
  1175. assertEquals(20.0, c1.getNumericCellValue(), 0);
  1176. assertEquals("SUM(Sheet1!C1,Sheet2!C1,Sheet3!C1,Sheet4!C1)", c1.getCellFormula());
  1177. assertEquals(20.0, c2.getNumericCellValue(), 0);
  1178. assertEquals("SUM(Sheet1:Sheet4!C1)", c2.getCellFormula());
  1179. // Try evaluating both
  1180. XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb);
  1181. eval.evaluateFormulaCell(c1);
  1182. eval.evaluateFormulaCell(c2);
  1183. assertEquals(20.0, c1.getNumericCellValue(), 0);
  1184. assertEquals(20.0, c2.getNumericCellValue(), 0);
  1185. }
  1186. }
  1187. /**
  1188. * Bugzilla 51710: problems reading shared formuals from .xlsx
  1189. */
  1190. @Test
  1191. public void bug51710() throws IOException {
  1192. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51710.xlsx")) {
  1193. final String[] columns = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"};
  1194. final int rowMax = 500; // bug triggers on row index 59
  1195. Sheet sheet = wb.getSheetAt(0);
  1196. // go through all formula cells
  1197. for (int rInd = 2; rInd <= rowMax; rInd++) {
  1198. Row row = sheet.getRow(rInd);
  1199. for (int cInd = 1; cInd <= 12; cInd++) {
  1200. Cell cell = row.getCell(cInd);
  1201. String formula = cell.getCellFormula();
  1202. CellReference ref = new CellReference(cell);
  1203. //simulate correct answer
  1204. String correct = "$A" + (rInd + 1) + "*" + columns[cInd] + "$2";
  1205. assertEquals("Incorrect formula in " + ref.formatAsString(), correct, formula);
  1206. }
  1207. }
  1208. }
  1209. }
  1210. /**
  1211. * Bug 53101:
  1212. */
  1213. @Test
  1214. public void bug5301() throws IOException {
  1215. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53101.xlsx")) {
  1216. FormulaEvaluator evaluator =
  1217. wb.getCreationHelper().createFormulaEvaluator();
  1218. // A1: SUM(B1: IZ1)
  1219. double a1Value =
  1220. evaluator.evaluate(wb.getSheetAt(0).getRow(0).getCell(0)).getNumberValue();
  1221. // Assert
  1222. assertEquals(259.0, a1Value, 0.0);
  1223. // KY: SUM(B1: IZ1)
  1224. /*double ky1Value =*/
  1225. assertEquals(259.0, evaluator.evaluate(wb.getSheetAt(0).getRow(0).getCell(310)).getNumberValue(), 0.0001);
  1226. // Assert
  1227. assertEquals(259.0, a1Value, 0.0);
  1228. }
  1229. }
  1230. @Test
  1231. public void bug54436() throws IOException {
  1232. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54436.xlsx")) {
  1233. if (!WorkbookEvaluator.getSupportedFunctionNames().contains("GETPIVOTDATA")) {
  1234. Function func = (args, srcRowIndex, srcColumnIndex) -> ErrorEval.NA;
  1235. WorkbookEvaluator.registerFunction("GETPIVOTDATA", func);
  1236. }
  1237. wb.getCreationHelper().createFormulaEvaluator().evaluateAll();
  1238. }
  1239. }
  1240. /**
  1241. * Password Protected .xlsx files are now (as of 4.0.0) tested for the default password
  1242. * when opened via WorkbookFactory, so there's no EncryptedDocumentException thrown anymore
  1243. */
  1244. @Test
  1245. public void bug55692_poifs() throws IOException {
  1246. // Via a POIFSFileSystem
  1247. try (POIFSFileSystem fsP = new POIFSFileSystem(
  1248. POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"))) {
  1249. WorkbookFactory.create(fsP);
  1250. }
  1251. }
  1252. @Test
  1253. public void bug55692_stream() throws IOException {
  1254. // Directly on a Stream, will go via POIFS and spot it's
  1255. // actually a .xlsx file encrypted with the default password, and open
  1256. try (Workbook wb = WorkbookFactory.create(
  1257. POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"))) {
  1258. assertNotNull(wb);
  1259. assertEquals(3, wb.getNumberOfSheets());
  1260. }
  1261. }
  1262. @Test
  1263. public void bug55692_poifs2() throws IOException {
  1264. // Via a POIFSFileSystem, will spot it's actually a .xlsx file
  1265. // encrypted with the default password, and open
  1266. try (POIFSFileSystem fsNP = new POIFSFileSystem(
  1267. POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"))) {
  1268. Workbook wb = WorkbookFactory.create(fsNP);
  1269. assertNotNull(wb);
  1270. assertEquals(3, wb.getNumberOfSheets());
  1271. wb.close();
  1272. }
  1273. }
  1274. @Test
  1275. public void bug53282() throws IOException {
  1276. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53282b.xlsx")) {
  1277. Cell c = wb.getSheetAt(0).getRow(1).getCell(0);
  1278. assertEquals("#@_#", c.getStringCellValue());
  1279. assertEquals("http://invalid.uri", c.getHyperlink().getAddress());
  1280. }
  1281. }
  1282. /**
  1283. * Was giving NullPointerException
  1284. * at org.apache.poi.xssf.usermodel.XSSFWorkbook.onDocumentRead
  1285. * due to a lack of Styles Table
  1286. */
  1287. @Test
  1288. public void bug56278() throws IOException {
  1289. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56278.xlsx")) {
  1290. assertEquals(0, wb.getSheetIndex("Market Rates"));
  1291. // Save and re-check
  1292. Workbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1293. assertEquals(0, nwb.getSheetIndex("Market Rates"));
  1294. nwb.close();
  1295. }
  1296. }
  1297. @Test
  1298. public void bug56315() throws IOException {
  1299. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56315.xlsx")) {
  1300. Cell c = wb.getSheetAt(0).getRow(1).getCell(0);
  1301. CellValue cv = wb.getCreationHelper().createFormulaEvaluator().evaluate(c);
  1302. double rounded = cv.getNumberValue();
  1303. assertEquals(0.1, rounded, 0.0);
  1304. }
  1305. }
  1306. @Test
  1307. public void bug56468() throws IOException, InterruptedException {
  1308. XSSFWorkbook wb = new XSSFWorkbook();
  1309. XSSFSheet sheet = wb.createSheet();
  1310. XSSFRow row = sheet.createRow(0);
  1311. XSSFCell cell = row.createCell(0);
  1312. cell.setCellValue("Hi");
  1313. sheet.setRepeatingRows(new CellRangeAddress(0, 0, 0, 0));
  1314. // small hack to try to make this test stable, previously it failed whenever the two written ZIP files had different file-creation
  1315. // dates stored.
  1316. // 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
  1317. // causes differences
  1318. long start = System.currentTimeMillis() / 1000;
  1319. while (System.currentTimeMillis() / 1000 == start) {
  1320. Thread.sleep(10);
  1321. }
  1322. ByteArrayOutputStream bos = new ByteArrayOutputStream(8096);
  1323. wb.write(bos);
  1324. byte[] firstSave = bos.toByteArray();
  1325. bos.reset();
  1326. wb.write(bos);
  1327. byte[] secondSave = bos.toByteArray();
  1328. /*OutputStream stream = new FileOutputStream("C:\\temp\\poi.xlsx");
  1329. try {
  1330. wb.write(stream);
  1331. } finally {
  1332. stream.close();
  1333. }*/
  1334. assertArrayEquals("Had: \n" + Arrays.toString(firstSave) + " and \n" + Arrays.toString(secondSave),
  1335. firstSave, secondSave);
  1336. wb.close();
  1337. }
  1338. /**
  1339. * ISO-8601 style cell formats with a T in them, eg
  1340. * cell format of "yyyy-MM-ddTHH:mm:ss"
  1341. */
  1342. @Test
  1343. public void bug54034() throws IOException {
  1344. TimeZone tz = LocaleUtil.getUserTimeZone();
  1345. LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET"));
  1346. try {
  1347. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54034.xlsx")) {
  1348. Sheet sheet = wb.getSheet("Sheet1");
  1349. Row row = sheet.getRow(1);
  1350. Cell cell = row.getCell(2);
  1351. assertTrue(DateUtil.isCellDateFormatted(cell));
  1352. DataFormatter fmt = new DataFormatter();
  1353. assertEquals("yyyy\\-mm\\-dd\\Thh:mm", cell.getCellStyle().getDataFormatString());
  1354. assertEquals("2012-08-08T22:59", fmt.formatCellValue(cell));
  1355. }
  1356. } finally {
  1357. LocaleUtil.setUserTimeZone(tz);
  1358. }
  1359. }
  1360. @Test
  1361. public void testBug53798XLSX() throws IOException {
  1362. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx")) {
  1363. File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx");
  1364. bug53798Work(wb, xlsOutput);
  1365. }
  1366. }
  1367. @Ignore("Shifting rows is not yet implemented in SXSSFSheet")
  1368. @Test
  1369. public void testBug53798XLSXStream() throws IOException {
  1370. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx")) {
  1371. File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx");
  1372. SXSSFWorkbook wb2 = new SXSSFWorkbook(wb);
  1373. bug53798Work(wb2, xlsOutput);
  1374. wb2.close();
  1375. }
  1376. }
  1377. @Test
  1378. public void testBug53798XLS() throws IOException {
  1379. Workbook wb = HSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xls");
  1380. File xlsOutput = TempFile.createTempFile("testBug53798", ".xls");
  1381. bug53798Work(wb, xlsOutput);
  1382. wb.close();
  1383. }
  1384. /**
  1385. * SUMIF was throwing a NPE on some formulas
  1386. */
  1387. @Test
  1388. public void testBug56420SumIfNPE() throws IOException {
  1389. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56420.xlsx")) {
  1390. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  1391. Sheet sheet = wb.getSheetAt(0);
  1392. Row r = sheet.getRow(2);
  1393. Cell c = r.getCell(2);
  1394. assertEquals("SUMIF($A$1:$A$4,A3,$B$1:$B$4)", c.getCellFormula());
  1395. Cell eval = evaluator.evaluateInCell(c);
  1396. assertEquals(0.0, eval.getNumericCellValue(), 0.0001);
  1397. }
  1398. }
  1399. private void bug53798Work(Workbook wb, File xlsOutput) throws IOException {
  1400. Sheet testSheet = wb.getSheetAt(0);
  1401. testSheet.shiftRows(2, 2, 1);
  1402. saveAndReloadReport(wb, xlsOutput);
  1403. // 1) corrupted xlsx (unreadable data in the first row of a shifted group) already comes about
  1404. // when shifted by less than -1 negative amount (try -2)
  1405. testSheet.shiftRows(3, 3, -1);
  1406. saveAndReloadReport(wb, xlsOutput);
  1407. testSheet.shiftRows(2, 2, 1);
  1408. saveAndReloadReport(wb, xlsOutput);
  1409. // 2) attempt to create a new row IN PLACE of a removed row by a negative shift causes corrupted
  1410. // xlsx file with unreadable data in the negative shifted row.
  1411. // NOTE it's ok to create any other row.
  1412. Row newRow = testSheet.createRow(3);
  1413. saveAndReloadReport(wb, xlsOutput);
  1414. Cell newCell = newRow.createCell(0);
  1415. saveAndReloadReport(wb, xlsOutput);
  1416. newCell.setCellValue("new Cell in row " + newRow.getRowNum());
  1417. saveAndReloadReport(wb, xlsOutput);
  1418. // 3) once a negative shift has been made any attempt to shift another group of rows
  1419. // (note: outside of previously negative shifted rows) by a POSITIVE amount causes POI exception:
  1420. // org.apache.xmlbeans.impl.values.XmlValueDisconnectedException.
  1421. // NOTE: another negative shift on another group of rows is successful, provided no new rows in
  1422. // place of previously shifted rows were attempted to be created as explained above.
  1423. testSheet.shiftRows(6, 7, 1); // -- CHANGE the shift to positive once the behaviour of
  1424. // the above has been tested
  1425. saveAndReloadReport(wb, xlsOutput);
  1426. }
  1427. /**
  1428. * XSSFCell.typeMismatch on certain blank cells when formatting
  1429. * with DataFormatter
  1430. */
  1431. @Test
  1432. public void bug56702() throws IOException {
  1433. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56702.xlsx")) {
  1434. Sheet sheet = wb.getSheetAt(0);
  1435. // Get wrong cell by row 8 & column 7
  1436. Cell cell = sheet.getRow(8).getCell(7);
  1437. assertEquals(CellType.NUMERIC, cell.getCellType());
  1438. // Check the value - will be zero as it is <c><v/></c>
  1439. assertEquals(0.0, cell.getNumericCellValue(), 0.001);
  1440. // Try to format
  1441. DataFormatter formatter = new DataFormatter();
  1442. formatter.formatCellValue(cell);
  1443. // Check the formatting
  1444. assertEquals("0", formatter.formatCellValue(cell));
  1445. }
  1446. }
  1447. /**
  1448. * Formulas which reference named ranges, either in other
  1449. * sheets, or workbook scoped but in other workbooks.
  1450. * Used to fail with with errors like
  1451. * org.apache.poi.ss.formula.FormulaParseException: Cell reference expected after sheet name at index 9
  1452. * org.apache.poi.ss.formula.FormulaParseException: Parse error near char 0 '[' in specified formula '[0]!NR_Global_B2'. Expected number, string, or defined name
  1453. */
  1454. @Test
  1455. public void bug56737() throws IOException {
  1456. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56737.xlsx")) {
  1457. // Check the named range definitions
  1458. Name nSheetScope = wb.getName("NR_To_A1");
  1459. Name nWBScope = wb.getName("NR_Global_B2");
  1460. assertNotNull(nSheetScope);
  1461. assertNotNull(nWBScope);
  1462. assertEquals("Defines!$A$1", nSheetScope.getRefersToFormula());
  1463. assertEquals("Defines!$B$2", nWBScope.getRefersToFormula());
  1464. // Check the different kinds of formulas
  1465. Sheet s = wb.getSheetAt(0);
  1466. Cell cRefSName = s.getRow(1).getCell(3);
  1467. Cell cRefWName = s.getRow(2).getCell(3);
  1468. assertEquals("Defines!NR_To_A1", cRefSName.getCellFormula());
  1469. // Note the formula, as stored in the file, has the external name index not filename
  1470. // TODO Provide a way to get the one with the filename
  1471. assertEquals("[0]!NR_Global_B2", cRefWName.getCellFormula());
  1472. // Try to evaluate them
  1473. FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator();
  1474. assertEquals("Test A1", eval.evaluate(cRefSName).getStringValue());
  1475. assertEquals(142, (int) eval.evaluate(cRefWName).getNumberValue());
  1476. // Try to evaluate everything
  1477. eval.evaluateAll();
  1478. }
  1479. }
  1480. private void saveAndReloadReport(Workbook wb, File outFile) throws IOException {
  1481. // run some method on the font to verify if it is "disconnected" already
  1482. //for(short i = 0;i < 256;i++)
  1483. {
  1484. Font font = wb.getFontAt(0);
  1485. if (font instanceof XSSFFont) {
  1486. XSSFFont xfont = (XSSFFont) wb.getFontAt(0);
  1487. CTFontImpl ctFont = (CTFontImpl) xfont.getCTFont();
  1488. assertEquals(0, ctFont.sizeOfBArray());
  1489. }
  1490. }
  1491. try (FileOutputStream fileOutStream = new FileOutputStream(outFile)) {
  1492. wb.write(fileOutStream);
  1493. }
  1494. try (FileInputStream is = new FileInputStream(outFile)) {
  1495. Workbook newWB = null;
  1496. try {
  1497. if (wb instanceof XSSFWorkbook) {
  1498. newWB = new XSSFWorkbook(is);
  1499. } else if (wb instanceof HSSFWorkbook) {
  1500. newWB = new HSSFWorkbook(is);
  1501. } else if (wb instanceof SXSSFWorkbook) {
  1502. newWB = new SXSSFWorkbook(new XSSFWorkbook(is));
  1503. } else {
  1504. throw new IllegalStateException("Unknown workbook: " + wb);
  1505. }
  1506. assertNotNull(newWB.getSheet("test"));
  1507. } finally {
  1508. if (newWB != null) {
  1509. newWB.close();
  1510. }
  1511. }
  1512. }
  1513. }
  1514. @Test
  1515. public void testBug56688_1() throws IOException {
  1516. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_1.xlsx");
  1517. checkValue(excel, "-1.0"); /* Not 0.0 because POI sees date "0" minus one month as invalid date, which is -1! */
  1518. excel.close();
  1519. }
  1520. @Test
  1521. public void testBug56688_2() throws IOException {
  1522. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_2.xlsx");
  1523. checkValue(excel, "#VALUE!");
  1524. excel.close();
  1525. }
  1526. @Test
  1527. public void testBug56688_3() throws IOException {
  1528. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_3.xlsx");
  1529. checkValue(excel, "#VALUE!");
  1530. excel.close();
  1531. }
  1532. @Test
  1533. public void testBug56688_4() throws IOException {
  1534. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_4.xlsx");
  1535. Calendar calendar = LocaleUtil.getLocaleCalendar();
  1536. calendar.add(Calendar.MONTH, 2);
  1537. double excelDate = DateUtil.getExcelDate(calendar.getTime());
  1538. NumberEval eval = new NumberEval(Math.floor(excelDate));
  1539. checkValue(excel, eval.getStringValue() + ".0");
  1540. excel.close();
  1541. }
  1542. /**
  1543. * New hyperlink with no initial cell reference, still need
  1544. * to be able to change it
  1545. */
  1546. @Test
  1547. public void testBug56527() throws IOException {
  1548. XSSFWorkbook wb = new XSSFWorkbook();
  1549. XSSFSheet sheet = wb.createSheet();
  1550. XSSFCreationHelper creationHelper = wb.getCreationHelper();
  1551. XSSFHyperlink hyperlink;
  1552. // Try with a cell reference
  1553. hyperlink = creationHelper.createHyperlink(HyperlinkType.URL);
  1554. sheet.addHyperlink(hyperlink);
  1555. hyperlink.setAddress("http://myurl");
  1556. hyperlink.setCellReference("B4");
  1557. assertEquals(3, hyperlink.getFirstRow());
  1558. assertEquals(1, hyperlink.getFirstColumn());
  1559. assertEquals(3, hyperlink.getLastRow());
  1560. assertEquals(1, hyperlink.getLastColumn());
  1561. // Try with explicit rows / columns
  1562. hyperlink = creationHelper.createHyperlink(HyperlinkType.URL);
  1563. sheet.addHyperlink(hyperlink);
  1564. hyperlink.setAddress("http://myurl");
  1565. hyperlink.setFirstRow(5);
  1566. hyperlink.setFirstColumn(3);
  1567. assertEquals(5, hyperlink.getFirstRow());
  1568. assertEquals(3, hyperlink.getFirstColumn());
  1569. assertEquals(5, hyperlink.getLastRow());
  1570. assertEquals(3, hyperlink.getLastColumn());
  1571. wb.close();
  1572. }
  1573. /**
  1574. * Shifting rows with a formula that references a
  1575. * function in another file
  1576. */
  1577. @Test
  1578. public void bug56502() throws IOException {
  1579. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56502.xlsx")) {
  1580. Sheet sheet = wb.getSheetAt(0);
  1581. Cell cFunc = sheet.getRow(3).getCell(0);
  1582. assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula());
  1583. Cell cRef = sheet.getRow(3).createCell(1);
  1584. cRef.setCellFormula("A3");
  1585. // Shift it down one row
  1586. sheet.shiftRows(1, sheet.getLastRowNum(), 1);
  1587. // Check the new formulas: Function won't change, Reference will
  1588. cFunc = sheet.getRow(4).getCell(0);
  1589. assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula());
  1590. cRef = sheet.getRow(4).getCell(1);
  1591. assertEquals("A4", cRef.getCellFormula());
  1592. }
  1593. }
  1594. @Test
  1595. public void bug54764() throws IOException, OpenXML4JException, XmlException {
  1596. OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("54764.xlsx");
  1597. // Check the core properties - will be found but empty, due
  1598. // to the expansion being too much to be considered valid
  1599. POIXMLProperties props = new POIXMLProperties(pkg);
  1600. assertNull(props.getCoreProperties().getTitle());
  1601. assertNull(props.getCoreProperties().getSubject());
  1602. assertNull(props.getCoreProperties().getDescription());
  1603. // Now check the spreadsheet itself
  1604. try {
  1605. new XSSFWorkbook(pkg).close();
  1606. fail("Should fail as too much expansion occurs");
  1607. } catch (POIXMLException e) {
  1608. // Expected
  1609. }
  1610. pkg.close();
  1611. // Try with one with the entities in the Content Types
  1612. try {
  1613. XSSFTestDataSamples.openSamplePackage("54764-2.xlsx").close();
  1614. fail("Should fail as too much expansion occurs");
  1615. } catch (Exception e) {
  1616. // Expected
  1617. }
  1618. // Check we can still parse valid files after all that
  1619. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx")) {
  1620. assertEquals(3, wb.getNumberOfSheets());
  1621. }
  1622. }
  1623. @Test
  1624. public void test54764WithSAXHelper() throws Exception {
  1625. File testFile = XSSFTestDataSamples.getSampleFile("54764.xlsx");
  1626. try (ZipFile zip = new ZipFile(testFile)) {
  1627. ZipArchiveEntry ze = zip.getEntry("xl/sharedStrings.xml");
  1628. XMLReader reader = XMLHelper.newXMLReader();
  1629. try {
  1630. reader.parse(new InputSource(zip.getInputStream(ze)));
  1631. fail("should have thrown SAXParseException");
  1632. } catch (SAXParseException e) {
  1633. assertNotNull(e.getMessage());
  1634. assertTrue(e.getMessage().contains("more than \"1\" entity"));
  1635. }
  1636. }
  1637. }
  1638. @Test
  1639. public void test54764WithDocumentHelper() throws Exception {
  1640. File testFile = XSSFTestDataSamples.getSampleFile("54764.xlsx");
  1641. try (ZipFile zip = new ZipFile(testFile)) {
  1642. ZipArchiveEntry ze = zip.getEntry("xl/sharedStrings.xml");
  1643. try {
  1644. DocumentHelper.readDocument(zip.getInputStream(ze));
  1645. fail("should have thrown SAXParseException");
  1646. } catch (SAXParseException e) {
  1647. assertNotNull(e.getMessage());
  1648. assertNotEquals(isOldXercesActive(), e.getMessage().contains("DOCTYPE is disallowed when the feature"));
  1649. }
  1650. }
  1651. }
  1652. /**
  1653. * CTDefinedNamesImpl should be included in the smaller
  1654. * poi-ooxml-schemas jar
  1655. */
  1656. @Test
  1657. public void bug57176() throws IOException {
  1658. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57176.xlsx")) {
  1659. CTDefinedNames definedNames = wb.getCTWorkbook().getDefinedNames();
  1660. List<CTDefinedName> definedNameList = definedNames.getDefinedNameList();
  1661. for (CTDefinedName defName : definedNameList) {
  1662. assertNotNull(defName.getName());
  1663. assertNotNull(defName.getStringValue());
  1664. }
  1665. assertEquals("TestDefinedName", definedNameList.get(0).getName());
  1666. }
  1667. }
  1668. /**
  1669. * .xlsb files are not supported, but we should generate a helpful
  1670. * error message if given one
  1671. */
  1672. @Test
  1673. public void bug56800_xlsb() throws IOException {
  1674. // Can be opened at the OPC level
  1675. OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("Simple.xlsb");
  1676. // XSSF Workbook gives helpful error
  1677. try {
  1678. new XSSFWorkbook(pkg).close();
  1679. fail(".xlsb files not supported");
  1680. } catch (XLSBUnsupportedException e) {
  1681. // Good, detected and warned
  1682. }
  1683. // Workbook Factory gives helpful error on package
  1684. try {
  1685. XSSFWorkbookFactory.create(pkg).close();
  1686. fail(".xlsb files not supported");
  1687. } catch (XLSBUnsupportedException e) {
  1688. // Good, detected and warned
  1689. }
  1690. // Workbook Factory gives helpful error on file
  1691. File xlsbFile = HSSFTestDataSamples.getSampleFile("Simple.xlsb");
  1692. try {
  1693. WorkbookFactory.create(xlsbFile).close();
  1694. fail(".xlsb files not supported");
  1695. } catch (XLSBUnsupportedException e) {
  1696. // Good, detected and warned
  1697. }
  1698. pkg.close();
  1699. }
  1700. private void checkValue(XSSFWorkbook excel, String expect) {
  1701. XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(excel);
  1702. evaluator.evaluateAll();
  1703. XSSFCell cell = excel.getSheetAt(0).getRow(1).getCell(1);
  1704. CellValue value = evaluator.evaluate(cell);
  1705. assertEquals(expect, value.formatAsString());
  1706. }
  1707. @Test
  1708. public void testBug57196() throws IOException {
  1709. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57196.xlsx")) {
  1710. Sheet sheet = wb.getSheet("Feuil1");
  1711. Row mod = sheet.getRow(1);
  1712. mod.getCell(1).setCellValue(3);
  1713. HSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
  1714. // FileOutputStream fileOutput = new FileOutputStream("/tmp/57196.xlsx");
  1715. // wb.write(fileOutput);
  1716. // fileOutput.close();
  1717. }
  1718. }
  1719. @Test
  1720. public void test57196_Detail() throws IOException {
  1721. XSSFWorkbook wb = new XSSFWorkbook();
  1722. XSSFSheet sheet = wb.createSheet("Sheet1");
  1723. XSSFRow row = sheet.createRow(0);
  1724. XSSFCell cell = row.createCell(0);
  1725. cell.setCellFormula("DEC2HEX(HEX2DEC(O8)-O2+D2)");
  1726. XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb);
  1727. CellValue cv = fe.evaluate(cell);
  1728. assertNotNull(cv);
  1729. wb.close();
  1730. }
  1731. @Test
  1732. public void test57196_Detail2() throws IOException {
  1733. XSSFWorkbook wb = new XSSFWorkbook();
  1734. XSSFSheet sheet = wb.createSheet("Sheet1");
  1735. XSSFRow row = sheet.createRow(0);
  1736. XSSFCell cell = row.createCell(0);
  1737. cell.setCellFormula("DEC2HEX(O2+D2)");
  1738. XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb);
  1739. CellValue cv = fe.evaluate(cell);
  1740. assertNotNull(cv);
  1741. wb.close();
  1742. }
  1743. @Test
  1744. public void test57196_WorkbookEvaluator() throws IOException {
  1745. String previousLogger = System.getProperty("org.apache.poi.util.POILogger");
  1746. //System.setProperty("org.apache.poi.util.POILogger", "org.apache.poi.util.SystemOutLogger");
  1747. //System.setProperty("poi.log.level", "3");
  1748. try {
  1749. XSSFWorkbook wb = new XSSFWorkbook();
  1750. XSSFSheet sheet = wb.createSheet("Sheet1");
  1751. XSSFRow row = sheet.createRow(0);
  1752. XSSFCell cell = row.createCell(0);
  1753. cell.setCellValue("0");
  1754. cell = row.createCell(1);
  1755. cell.setCellValue(0);
  1756. cell = row.createCell(2);
  1757. cell.setCellValue(0);
  1758. // simple formula worked
  1759. cell.setCellFormula("DEC2HEX(O2+D2)");
  1760. WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1761. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1762. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1763. // this already failed! Hex2Dec did not correctly handle RefEval
  1764. cell.setCellFormula("HEX2DEC(O8)");
  1765. workbookEvaluator.clearAllCachedResultValues();
  1766. workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1767. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1768. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1769. // slightly more complex one failed
  1770. cell.setCellFormula("HEX2DEC(O8)-O2+D2");
  1771. workbookEvaluator.clearAllCachedResultValues();
  1772. workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1773. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1774. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1775. // more complicated failed
  1776. cell.setCellFormula("DEC2HEX(HEX2DEC(O8)-O2+D2)");
  1777. workbookEvaluator.clearAllCachedResultValues();
  1778. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1779. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1780. // what other similar functions
  1781. cell.setCellFormula("DEC2BIN(O8)-O2+D2");
  1782. workbookEvaluator.clearAllCachedResultValues();
  1783. workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1784. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1785. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1786. // what other similar functions
  1787. cell.setCellFormula("DEC2BIN(A1)");
  1788. workbookEvaluator.clearAllCachedResultValues();
  1789. workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1790. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1791. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1792. // what other similar functions
  1793. cell.setCellFormula("BIN2DEC(B1)");
  1794. workbookEvaluator.clearAllCachedResultValues();
  1795. workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1796. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1797. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1798. wb.close();
  1799. } finally {
  1800. if (previousLogger == null) {
  1801. System.clearProperty("org.apache.poi.util.POILogger");
  1802. } else {
  1803. System.setProperty("org.apache.poi.util.POILogger", previousLogger);
  1804. }
  1805. System.clearProperty("poi.log.level");
  1806. }
  1807. }
  1808. /**
  1809. * A .xlsx file with no Shared Strings table should open fine
  1810. * in read-only mode
  1811. */
  1812. @SuppressWarnings("resource")
  1813. @Test
  1814. public void bug57482() throws IOException, InvalidFormatException {
  1815. for (PackageAccess access : new PackageAccess[]{
  1816. PackageAccess.READ_WRITE, PackageAccess.READ
  1817. }) {
  1818. File file = HSSFTestDataSamples.getSampleFile("57482-OnlyNumeric.xlsx");
  1819. OPCPackage pkg = OPCPackage.open(file, access);
  1820. try {
  1821. // Try to open it and read the contents
  1822. XSSFWorkbook wb1 = new XSSFWorkbook(pkg);
  1823. assertNotNull(wb1.getSharedStringSource());
  1824. assertEquals(0, wb1.getSharedStringSource().getCount());
  1825. DataFormatter fmt = new DataFormatter();
  1826. XSSFSheet s = wb1.getSheetAt(0);
  1827. assertEquals("1", fmt.formatCellValue(s.getRow(0).getCell(0)));
  1828. assertEquals("11", fmt.formatCellValue(s.getRow(0).getCell(1)));
  1829. assertEquals("5", fmt.formatCellValue(s.getRow(4).getCell(0)));
  1830. // Add a text cell
  1831. s.getRow(0).createCell(3).setCellValue("Testing");
  1832. assertEquals("Testing", fmt.formatCellValue(s.getRow(0).getCell(3)));
  1833. // Try to write-out and read again, should only work
  1834. // in read-write mode, not read-only mode
  1835. XSSFWorkbook wb2 = null;
  1836. try {
  1837. wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  1838. if (access == PackageAccess.READ) {
  1839. fail("Shouln't be able to write from read-only mode");
  1840. }
  1841. // Check again
  1842. s = wb2.getSheetAt(0);
  1843. assertEquals("1", fmt.formatCellValue(s.getRow(0).getCell(0)));
  1844. assertEquals("11", fmt.formatCellValue(s.getRow(0).getCell(1)));
  1845. assertEquals("5", fmt.formatCellValue(s.getRow(4).getCell(0)));
  1846. assertEquals("Testing", fmt.formatCellValue(s.getRow(0).getCell(3)));
  1847. } catch (InvalidOperationException e) {
  1848. if (access == PackageAccess.READ_WRITE) {
  1849. // Shouldn't occur in write-mode
  1850. throw e;
  1851. }
  1852. } finally {
  1853. if (wb2 != null) {
  1854. wb2.getPackage().revert();
  1855. }
  1856. }
  1857. wb1.getPackage().revert();
  1858. } finally {
  1859. pkg.revert();
  1860. }
  1861. }
  1862. }
  1863. /**
  1864. * "Unknown error type: -60" fetching formula error value
  1865. */
  1866. @Test
  1867. public void bug57535() throws IOException {
  1868. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57535.xlsx")) {
  1869. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  1870. evaluator.clearAllCachedResultValues();
  1871. Sheet sheet = wb.getSheet("Sheet1");
  1872. Cell cell = sheet.getRow(5).getCell(4);
  1873. assertEquals(CellType.FORMULA, cell.getCellType());
  1874. assertEquals("E4+E5", cell.getCellFormula());
  1875. CellValue value = evaluator.evaluate(cell);
  1876. assertEquals(CellType.ERROR, value.getCellType());
  1877. assertEquals(-60, value.getErrorValue());
  1878. assertEquals("~CIRCULAR~REF~", FormulaError.forInt(value.getErrorValue()).getString());
  1879. assertEquals("CIRCULAR_REF", FormulaError.forInt(value.getErrorValue()).toString());
  1880. }
  1881. }
  1882. @Test
  1883. public void test57165() throws IOException {
  1884. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx")) {
  1885. removeAllSheetsBut(3, wb);
  1886. wb.cloneSheet(0); // Throws exception here
  1887. wb.setSheetName(1, "New Sheet");
  1888. //saveWorkbook(wb, fileName);
  1889. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1890. wbBack.close();
  1891. }
  1892. }
  1893. @Test
  1894. public void test57165_create() throws IOException {
  1895. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx")) {
  1896. removeAllSheetsBut(3, wb);
  1897. wb.createSheet("newsheet"); // Throws exception here
  1898. wb.setSheetName(1, "New Sheet");
  1899. //saveWorkbook(wb, fileName);
  1900. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1901. wbBack.close();
  1902. }
  1903. }
  1904. private static void removeAllSheetsBut(@SuppressWarnings("SameParameterValue") int sheetIndex, Workbook wb) {
  1905. int sheetNb = wb.getNumberOfSheets();
  1906. // Move this sheet at the first position
  1907. wb.setSheetOrder(wb.getSheetName(sheetIndex), 0);
  1908. for (int sn = sheetNb - 1; sn > 0; sn--) {
  1909. wb.removeSheetAt(sn);
  1910. }
  1911. }
  1912. /**
  1913. * Sums 2 plus the cell at the left, indirectly to avoid reference
  1914. * problems when deleting columns, conditionally to stop recursion
  1915. */
  1916. private static final String FORMULA1 =
  1917. "IF( INDIRECT( ADDRESS( ROW(), COLUMN()-1 ) ) = 0, 0, "
  1918. + "INDIRECT( ADDRESS( ROW(), COLUMN()-1 ) ) ) + 2";
  1919. /**
  1920. * Sums 2 plus the upper cell, indirectly to avoid reference
  1921. * problems when deleting rows, conditionally to stop recursion
  1922. */
  1923. private static final String FORMULA2 =
  1924. "IF( INDIRECT( ADDRESS( ROW()-1, COLUMN() ) ) = 0, 0, "
  1925. + "INDIRECT( ADDRESS( ROW()-1, COLUMN() ) ) ) + 2";
  1926. /**
  1927. * Expected:
  1928. * <p>
  1929. * [ 0][ 2][ 4]
  1930. */
  1931. @Test
  1932. public void testBug56820_Formula1() throws IOException {
  1933. try (Workbook wb = new XSSFWorkbook()) {
  1934. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  1935. Sheet sh = wb.createSheet();
  1936. sh.createRow(0).createCell(0).setCellValue(0.0d);
  1937. Cell formulaCell1 = sh.getRow(0).createCell(1);
  1938. Cell formulaCell2 = sh.getRow(0).createCell(2);
  1939. formulaCell1.setCellFormula(FORMULA1);
  1940. formulaCell2.setCellFormula(FORMULA1);
  1941. double A1 = evaluator.evaluate(formulaCell1).getNumberValue();
  1942. double A2 = evaluator.evaluate(formulaCell2).getNumberValue();
  1943. assertEquals(2, A1, 0);
  1944. assertEquals(4, A2, 0); //<-- FAILS EXPECTATIONS
  1945. }
  1946. }
  1947. /**
  1948. * Expected:
  1949. * <p>
  1950. * [ 0] <- number
  1951. * [ 2] <- formula
  1952. * [ 4] <- formula
  1953. */
  1954. @Test
  1955. public void testBug56820_Formula2() throws IOException {
  1956. try (Workbook wb = new XSSFWorkbook()) {
  1957. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  1958. Sheet sh = wb.createSheet();
  1959. sh.createRow(0).createCell(0).setCellValue(0.0d);
  1960. Cell formulaCell1 = sh.createRow(1).createCell(0);
  1961. Cell formulaCell2 = sh.createRow(2).createCell(0);
  1962. formulaCell1.setCellFormula(FORMULA2);
  1963. formulaCell2.setCellFormula(FORMULA2);
  1964. double A1 = evaluator.evaluate(formulaCell1).getNumberValue();
  1965. double A2 = evaluator.evaluate(formulaCell2).getNumberValue(); //<-- FAILS EVALUATION
  1966. assertEquals(2, A1, 0);
  1967. assertEquals(4, A2, 0);
  1968. }
  1969. }
  1970. @Test
  1971. public void test56467() throws IOException {
  1972. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("picture.xlsx")) {
  1973. Sheet orig = wb.getSheetAt(0);
  1974. assertNotNull(orig);
  1975. Sheet sheet = wb.cloneSheet(0);
  1976. Drawing<?> drawing = sheet.createDrawingPatriarch();
  1977. for (XSSFShape shape : ((XSSFDrawing) drawing).getShapes()) {
  1978. if (shape instanceof XSSFPicture) {
  1979. XSSFPictureData pictureData = ((XSSFPicture) shape).getPictureData();
  1980. assertNotNull(pictureData);
  1981. }
  1982. }
  1983. }
  1984. }
  1985. /**
  1986. * OOXML-Strict files
  1987. * Not currently working - namespace mis-match from XMLBeans
  1988. */
  1989. @Test
  1990. @Ignore("XMLBeans namespace mis-match on ooxml-strict files")
  1991. public void test57699() throws IOException {
  1992. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.strict.xlsx")) {
  1993. assertEquals(3, wb.getNumberOfSheets());
  1994. // TODO Check sheet contents
  1995. // TODO Check formula evaluation
  1996. try (XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) {
  1997. assertEquals(3, wbBack.getNumberOfSheets());
  1998. // TODO Re-check sheet contents
  1999. // TODO Re-check formula evaluation
  2000. }
  2001. }
  2002. }
  2003. @Test
  2004. public void testBug56295_MergeXlslsWithStyles() throws IOException {
  2005. XSSFWorkbook xlsToAppendWorkbook = XSSFTestDataSamples.openSampleWorkbook("56295.xlsx");
  2006. XSSFSheet sheet = xlsToAppendWorkbook.getSheetAt(0);
  2007. XSSFRow srcRow = sheet.getRow(0);
  2008. XSSFCell oldCell = srcRow.getCell(0);
  2009. XSSFCellStyle cellStyle = oldCell.getCellStyle();
  2010. checkStyle(cellStyle);
  2011. // StylesTable table = xlsToAppendWorkbook.getStylesSource();
  2012. // List<XSSFCellFill> fills = table.getFills();
  2013. // System.out.println("Having " + fills.size() + " fills");
  2014. // for(XSSFCellFill fill : fills) {
  2015. // System.out.println("Fill: " + fill.getFillBackgroundColor() + "/" + fill.getFillForegroundColor());
  2016. // }
  2017. xlsToAppendWorkbook.close();
  2018. XSSFWorkbook targetWorkbook = new XSSFWorkbook();
  2019. XSSFSheet newSheet = targetWorkbook.createSheet(sheet.getSheetName());
  2020. XSSFRow destRow = newSheet.createRow(0);
  2021. XSSFCell newCell = destRow.createCell(0);
  2022. //newCell.getCellStyle().cloneStyleFrom(cellStyle);
  2023. CellStyle newCellStyle = targetWorkbook.createCellStyle();
  2024. newCellStyle.cloneStyleFrom(cellStyle);
  2025. newCell.setCellStyle(newCellStyle);
  2026. checkStyle(newCell.getCellStyle());
  2027. newCell.setCellValue(oldCell.getStringCellValue());
  2028. // OutputStream os = new FileOutputStream("output.xlsm");
  2029. // try {
  2030. // targetWorkbook.write(os);
  2031. // } finally {
  2032. // os.close();
  2033. // }
  2034. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(targetWorkbook);
  2035. XSSFCellStyle styleBack = wbBack.getSheetAt(0).getRow(0).getCell(0).getCellStyle();
  2036. checkStyle(styleBack);
  2037. targetWorkbook.close();
  2038. wbBack.close();
  2039. }
  2040. /**
  2041. * Paragraph with property BuFont but none of the properties
  2042. * BuNone, BuChar, and BuAutoNum, used to trigger a NPE
  2043. * Excel treats this as not-bulleted, so now do we
  2044. */
  2045. @Test
  2046. public void testBug57826() throws IOException {
  2047. XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("57826.xlsx");
  2048. assertTrue("no sheets in workbook", workbook.getNumberOfSheets() >= 1);
  2049. XSSFSheet sheet = workbook.getSheetAt(0);
  2050. XSSFDrawing drawing = sheet.getDrawingPatriarch();
  2051. assertNotNull(drawing);
  2052. List<XSSFShape> shapes = drawing.getShapes();
  2053. assertEquals(1, shapes.size());
  2054. assertTrue(shapes.get(0) instanceof XSSFSimpleShape);
  2055. XSSFSimpleShape shape = (XSSFSimpleShape) shapes.get(0);
  2056. // Used to throw a NPE
  2057. String text = shape.getText();
  2058. // No bulleting info included
  2059. assertEquals("test ok", text);
  2060. workbook.close();
  2061. }
  2062. private void checkStyle(XSSFCellStyle cellStyle) {
  2063. assertNotNull(cellStyle);
  2064. assertEquals(0, cellStyle.getFillForegroundColor());
  2065. assertNotNull(cellStyle.getFillForegroundXSSFColor());
  2066. XSSFColor fgColor = cellStyle.getFillForegroundColorColor();
  2067. assertNotNull(fgColor);
  2068. assertEquals("FF00FFFF", fgColor.getARGBHex());
  2069. assertEquals(0, cellStyle.getFillBackgroundColor());
  2070. assertNotNull(cellStyle.getFillBackgroundXSSFColor());
  2071. XSSFColor bgColor = cellStyle.getFillBackgroundColorColor();
  2072. assertNotNull(bgColor);
  2073. assertEquals("FF00FFFF", fgColor.getARGBHex());
  2074. }
  2075. @Test
  2076. public void bug57642() throws IOException {
  2077. XSSFWorkbook wb = new XSSFWorkbook();
  2078. XSSFSheet s = wb.createSheet("TestSheet");
  2079. XSSFCell c = s.createRow(0).createCell(0);
  2080. c.setCellFormula("ISERROR(TestSheet!A1)");
  2081. c = s.createRow(1).createCell(1);
  2082. c.setCellFormula("ISERROR(B2)");
  2083. wb.setSheetName(0, "CSN");
  2084. c = s.getRow(0).getCell(0);
  2085. assertEquals("ISERROR(CSN!A1)", c.getCellFormula());
  2086. c = s.getRow(1).getCell(1);
  2087. assertEquals("ISERROR(B2)", c.getCellFormula());
  2088. wb.close();
  2089. }
  2090. /**
  2091. * .xlsx supports 64000 cell styles, the style indexes after
  2092. * 32,767 must not be -32,768, then -32,767, -32,766
  2093. */
  2094. @Test
  2095. public void bug57880() throws IOException {
  2096. int numStyles = 33000;
  2097. XSSFWorkbook wb = new XSSFWorkbook();
  2098. for (int i = 1; i < numStyles; i++) {
  2099. // Create a style and use it
  2100. XSSFCellStyle style = wb.createCellStyle();
  2101. assertEquals(i, style.getUIndex());
  2102. }
  2103. assertEquals(numStyles, wb.getNumCellStyles());
  2104. // avoid OOM in Gump run
  2105. File file = XSSFTestDataSamples.writeOutAndClose(wb, "bug57880");
  2106. //noinspection UnusedAssignment
  2107. wb = null;
  2108. // Garbage collection may happen here
  2109. // avoid zip bomb detection
  2110. double ratio = ZipSecureFile.getMinInflateRatio();
  2111. ZipSecureFile.setMinInflateRatio(0.00005);
  2112. wb = XSSFTestDataSamples.readBackAndDelete(file);
  2113. ZipSecureFile.setMinInflateRatio(ratio);
  2114. //Assume identical cell styles aren't consolidated
  2115. //If XSSFWorkbooks ever implicitly optimize/consolidate cell styles (such as when the workbook is written to disk)
  2116. //then this unit test should be updated
  2117. assertEquals(numStyles, wb.getNumCellStyles());
  2118. for (int i = 1; i < numStyles; i++) {
  2119. XSSFCellStyle style = wb.getCellStyleAt(i);
  2120. assertNotNull(style);
  2121. assertEquals(i, style.getUIndex());
  2122. }
  2123. wb.close();
  2124. }
  2125. @Test
  2126. public void test56574() throws IOException {
  2127. runTest56574(false);
  2128. runTest56574(true);
  2129. }
  2130. private void runTest56574(boolean createRow) throws IOException {
  2131. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56574.xlsx")) {
  2132. Sheet sheet = wb.getSheet("Func");
  2133. assertNotNull(sheet);
  2134. Map<String, Object[]> data;
  2135. data = new TreeMap<>();
  2136. data.put("1", new Object[]{"ID", "NAME", "LASTNAME"});
  2137. data.put("2", new Object[]{2, "Amit", "Shukla"});
  2138. data.put("3", new Object[]{1, "Lokesh", "Gupta"});
  2139. data.put("4", new Object[]{4, "John", "Adwards"});
  2140. data.put("5", new Object[]{2, "Brian", "Schultz"});
  2141. int rownum = 1;
  2142. for (Map.Entry<String, Object[]> me : data.entrySet()) {
  2143. final Row row;
  2144. if (createRow) {
  2145. row = sheet.createRow(rownum++);
  2146. } else {
  2147. row = sheet.getRow(rownum++);
  2148. }
  2149. assertNotNull(row);
  2150. int cellnum = 0;
  2151. for (Object obj : me.getValue()) {
  2152. Cell cell = row.getCell(cellnum);
  2153. if (cell == null) {
  2154. cell = row.createCell(cellnum);
  2155. } else {
  2156. if (cell.getCellType() == CellType.FORMULA) {
  2157. cell.setCellFormula(null);
  2158. cell.getCellStyle().setDataFormat((short) 0);
  2159. }
  2160. }
  2161. if (obj instanceof String) {
  2162. cell.setCellValue((String) obj);
  2163. } else if (obj instanceof Integer) {
  2164. cell.setCellValue((Integer) obj);
  2165. }
  2166. cellnum++;
  2167. }
  2168. }
  2169. XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
  2170. wb.getCreationHelper().createFormulaEvaluator().evaluateAll();
  2171. CalculationChain chain = wb.getCalculationChain();
  2172. checkCellsAreGone(chain);
  2173. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  2174. Sheet sheetBack = wbBack.getSheet("Func");
  2175. assertNotNull(sheetBack);
  2176. chain = wbBack.getCalculationChain();
  2177. checkCellsAreGone(chain);
  2178. wbBack.close();
  2179. }
  2180. }
  2181. private void checkCellsAreGone(CalculationChain chain) {
  2182. for (CTCalcCell calc : chain.getCTCalcChain().getCList()) {
  2183. // A2 to A6 should be gone
  2184. assertNotEquals("A2", calc.getR());
  2185. assertNotEquals("A3", calc.getR());
  2186. assertNotEquals("A4", calc.getR());
  2187. assertNotEquals("A5", calc.getR());
  2188. assertNotEquals("A6", calc.getR());
  2189. }
  2190. }
  2191. /**
  2192. * Excel 2007 generated Macro-Enabled .xlsm file
  2193. */
  2194. @Test
  2195. public void bug57181() throws IOException {
  2196. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57181.xlsm")) {
  2197. assertEquals(9, wb.getNumberOfSheets());
  2198. }
  2199. }
  2200. @Test
  2201. public void bug52111() throws IOException {
  2202. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("Intersection-52111-xssf.xlsx")) {
  2203. Sheet s = wb.getSheetAt(0);
  2204. assertFormula(wb, s.getRow(2).getCell(0), "(C2:D3 D3:E4)", "4.0");
  2205. assertFormula(wb, s.getRow(6).getCell(0), "Tabelle2!E:E Tabelle2!11:11", "5.0");
  2206. assertFormula(wb, s.getRow(8).getCell(0), "Tabelle2!E:F Tabelle2!11:12", null);
  2207. }
  2208. }
  2209. @Test
  2210. public void test48962() throws IOException {
  2211. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("48962.xlsx")) {
  2212. Sheet sh = wb.getSheetAt(0);
  2213. Row row = sh.getRow(1);
  2214. Cell cell = row.getCell(0);
  2215. CellStyle style = cell.getCellStyle();
  2216. assertNotNull(style);
  2217. // color index
  2218. assertEquals(64, style.getFillBackgroundColor());
  2219. XSSFColor color = ((XSSFCellStyle) style).getFillBackgroundXSSFColor();
  2220. assertNotNull(color);
  2221. // indexed color
  2222. assertEquals(64, color.getIndexed());
  2223. assertEquals(64, color.getIndex());
  2224. // not an RGB color
  2225. assertFalse(color.isRGB());
  2226. assertNull(color.getRGB());
  2227. }
  2228. }
  2229. @Test
  2230. public void test50755_workday_formula_example() throws IOException {
  2231. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50755_workday_formula_example.xlsx")) {
  2232. Sheet sheet = wb.getSheet("Sheet1");
  2233. for (Row aRow : sheet) {
  2234. Cell cell = aRow.getCell(1);
  2235. if (cell.getCellType() == CellType.FORMULA) {
  2236. String formula = cell.getCellFormula();
  2237. assertNotNull(formula);
  2238. assertTrue(formula.contains("WORKDAY"));
  2239. } else {
  2240. assertNotNull(cell.toString());
  2241. }
  2242. }
  2243. }
  2244. }
  2245. @Test
  2246. public void test51626() throws IOException {
  2247. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51626.xlsx");
  2248. assertNotNull(wb);
  2249. wb.close();
  2250. InputStream stream = HSSFTestDataSamples.openSampleFileStream("51626.xlsx");
  2251. wb = WorkbookFactory.create(stream);
  2252. stream.close();
  2253. wb.close();
  2254. wb = XSSFTestDataSamples.openSampleWorkbook("51626_contact.xlsx");
  2255. assertNotNull(wb);
  2256. wb.close();
  2257. stream = HSSFTestDataSamples.openSampleFileStream("51626_contact.xlsx");
  2258. wb = WorkbookFactory.create(stream);
  2259. stream.close();
  2260. wb.close();
  2261. }
  2262. @Test
  2263. public void test51451() throws IOException {
  2264. Workbook wb = new XSSFWorkbook();
  2265. Sheet sh = wb.createSheet();
  2266. Row row = sh.createRow(0);
  2267. Cell cell = row.createCell(0);
  2268. cell.setCellValue(239827342);
  2269. CellStyle style = wb.createCellStyle();
  2270. //style.setHidden(false);
  2271. DataFormat excelFormat = wb.createDataFormat();
  2272. style.setDataFormat(excelFormat.getFormat("#,##0"));
  2273. sh.setDefaultColumnStyle(0, style);
  2274. // FileOutputStream out = new FileOutputStream("/tmp/51451.xlsx");
  2275. // wb.write(out);
  2276. // out.close();
  2277. wb.close();
  2278. }
  2279. @Test
  2280. public void test53105() throws IOException {
  2281. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53105.xlsx")) {
  2282. assertNotNull(wb);
  2283. // Act
  2284. // evaluate SUM('Skye Lookup Input'!A4:XFD4), cells in range each contain "1"
  2285. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  2286. double numericValue = evaluator.evaluate(wb.getSheetAt(0).getRow(1).getCell(0)).getNumberValue();
  2287. // Assert
  2288. assertEquals(16384.0, numericValue, 0.0);
  2289. }
  2290. }
  2291. @Test
  2292. public void test58315() throws IOException {
  2293. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58315.xlsx")) {
  2294. Cell cell = wb.getSheetAt(0).getRow(0).getCell(0);
  2295. assertNotNull(cell);
  2296. StringBuilder tmpCellContent = new StringBuilder(cell.getStringCellValue());
  2297. XSSFRichTextString richText = (XSSFRichTextString) cell.getRichStringCellValue();
  2298. for (int i = richText.length() - 1; i >= 0; i--) {
  2299. Font f = richText.getFontAtIndex(i);
  2300. if (f != null && f.getStrikeout()) {
  2301. tmpCellContent.deleteCharAt(i);
  2302. }
  2303. }
  2304. String result = tmpCellContent.toString();
  2305. assertEquals("320 350", result);
  2306. }
  2307. }
  2308. @Test
  2309. public void test55406() throws IOException {
  2310. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("55406_Conditional_formatting_sample.xlsx")) {
  2311. Sheet sheet = wb.getSheetAt(0);
  2312. Cell cellA1 = sheet.getRow(0).getCell(0);
  2313. Cell cellA2 = sheet.getRow(1).getCell(0);
  2314. assertEquals(0, cellA1.getCellStyle().getFillForegroundColor());
  2315. assertEquals("FFFDFDFD", ((XSSFColor) cellA1.getCellStyle().getFillForegroundColorColor()).getARGBHex());
  2316. assertEquals(0, cellA2.getCellStyle().getFillForegroundColor());
  2317. assertEquals("FFFDFDFD", ((XSSFColor) cellA2.getCellStyle().getFillForegroundColorColor()).getARGBHex());
  2318. SheetConditionalFormatting cond = sheet.getSheetConditionalFormatting();
  2319. assertEquals(2, cond.getNumConditionalFormattings());
  2320. assertEquals(1, cond.getConditionalFormattingAt(0).getNumberOfRules());
  2321. assertEquals(64, cond.getConditionalFormattingAt(0).getRule(0).getPatternFormatting().getFillForegroundColor());
  2322. assertEquals("ISEVEN(ROW())", cond.getConditionalFormattingAt(0).getRule(0).getFormula1());
  2323. assertNull(((XSSFColor) cond.getConditionalFormattingAt(0).getRule(0).getPatternFormatting().getFillForegroundColorColor()).getARGBHex());
  2324. assertEquals(1, cond.getConditionalFormattingAt(1).getNumberOfRules());
  2325. assertEquals(64, cond.getConditionalFormattingAt(1).getRule(0).getPatternFormatting().getFillForegroundColor());
  2326. assertEquals("ISEVEN(ROW())", cond.getConditionalFormattingAt(1).getRule(0).getFormula1());
  2327. assertNull(((XSSFColor) cond.getConditionalFormattingAt(1).getRule(0).getPatternFormatting().getFillForegroundColorColor()).getARGBHex());
  2328. }
  2329. }
  2330. @Test
  2331. public void test51998() throws IOException {
  2332. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51998.xlsx");
  2333. Set<String> sheetNames = new HashSet<>();
  2334. for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) {
  2335. sheetNames.add(wb.getSheetName(sheetNum));
  2336. }
  2337. for (String sheetName : sheetNames) {
  2338. int sheetIndex = wb.getSheetIndex(sheetName);
  2339. wb.removeSheetAt(sheetIndex);
  2340. Sheet newSheet = wb.createSheet();
  2341. //Sheet newSheet = wb.createSheet(sheetName);
  2342. int newSheetIndex = wb.getSheetIndex(newSheet);
  2343. wb.setSheetName(newSheetIndex, sheetName);
  2344. wb.setSheetOrder(sheetName, sheetIndex);
  2345. }
  2346. Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  2347. wb.close();
  2348. assertNotNull(wbBack);
  2349. wbBack.close();
  2350. }
  2351. @Test
  2352. public void test58731() throws IOException {
  2353. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58731.xlsx")) {
  2354. Sheet sheet = wb.createSheet("Java Books");
  2355. Object[][] bookData = {
  2356. {"Head First Java", "Kathy Serria", 79},
  2357. {"Effective Java", "Joshua Bloch", 36},
  2358. {"Clean Code", "Robert martin", 42},
  2359. {"Thinking in Java", "Bruce Eckel", 35},
  2360. };
  2361. int rowCount = 0;
  2362. for (Object[] aBook : bookData) {
  2363. Row row = sheet.createRow(rowCount++);
  2364. int columnCount = 0;
  2365. for (Object field : aBook) {
  2366. Cell cell = row.createCell(columnCount++);
  2367. if (field instanceof String) {
  2368. cell.setCellValue((String) field);
  2369. } else if (field instanceof Integer) {
  2370. cell.setCellValue((Integer) field);
  2371. }
  2372. }
  2373. }
  2374. try (Workbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb)) {
  2375. sheet = wb2.getSheet("Java Books");
  2376. assertNotNull(sheet.getRow(0));
  2377. assertNotNull(sheet.getRow(0).getCell(0));
  2378. assertEquals(bookData[0][0], sheet.getRow(0).getCell(0).getStringCellValue());
  2379. }
  2380. }
  2381. }
  2382. /**
  2383. * Regression between 3.10.1 and 3.13 -
  2384. * org.apache.poi.openxml4j.exceptions.InvalidFormatException:
  2385. * The part /xl/sharedStrings.xml does not have any content type
  2386. * ! Rule: Package require content types when retrieving a part from a package. [M.1.14]
  2387. */
  2388. @Test
  2389. public void test58760() throws IOException {
  2390. Workbook wb1 = XSSFTestDataSamples.openSampleWorkbook("58760.xlsx");
  2391. assertEquals(1, wb1.getNumberOfSheets());
  2392. assertEquals("Sheet1", wb1.getSheetName(0));
  2393. Workbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  2394. assertEquals(1, wb2.getNumberOfSheets());
  2395. assertEquals("Sheet1", wb2.getSheetName(0));
  2396. wb2.close();
  2397. wb1.close();
  2398. }
  2399. @Test
  2400. public void test57236() throws IOException {
  2401. // Having very small numbers leads to different formatting, Excel uses the scientific notation, but POI leads to "0"
  2402. /*
  2403. DecimalFormat format = new DecimalFormat("#.##########", new DecimalFormatSymbols(Locale.getDefault()));
  2404. double d = 3.0E-104;
  2405. assertEquals("3.0E-104", format.format(d));
  2406. */
  2407. DataFormatter formatter = new DataFormatter(true);
  2408. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57236.xlsx")) {
  2409. for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) {
  2410. Sheet sheet = wb.getSheetAt(sheetNum);
  2411. for (int rowNum = sheet.getFirstRowNum(); rowNum < sheet.getLastRowNum(); rowNum++) {
  2412. Row row = sheet.getRow(rowNum);
  2413. for (int cellNum = row.getFirstCellNum(); cellNum < row.getLastCellNum(); cellNum++) {
  2414. Cell cell = row.getCell(cellNum);
  2415. String fmtCellValue = formatter.formatCellValue(cell);
  2416. assertNotNull(fmtCellValue);
  2417. assertNotEquals("0", fmtCellValue);
  2418. }
  2419. }
  2420. }
  2421. }
  2422. }
  2423. /**
  2424. * helper function for {@link #test58043()}
  2425. * Side-effects: closes the provided workbook!
  2426. *
  2427. * @param workbook the workbook to save for manual checking
  2428. * @param outputFile the output file location to save the workbook to
  2429. */
  2430. private void saveRotatedTextExample(Workbook workbook, File outputFile) throws IOException {
  2431. Sheet sheet = workbook.createSheet();
  2432. Row row = sheet.createRow((short) 0);
  2433. Cell cell = row.createCell(0);
  2434. cell.setCellValue("Unsuccessful rotated text.");
  2435. CellStyle style = workbook.createCellStyle();
  2436. style.setRotation((short) -90);
  2437. cell.setCellStyle(style);
  2438. OutputStream fos = new FileOutputStream(outputFile);
  2439. workbook.write(fos);
  2440. fos.close();
  2441. workbook.close();
  2442. }
  2443. @Ignore("Creates files for checking results manually, actual values are tested in Test*CellStyle")
  2444. @Test
  2445. public void test58043() throws IOException {
  2446. saveRotatedTextExample(new HSSFWorkbook(), TempFile.createTempFile("rotated", ".xls"));
  2447. saveRotatedTextExample(new XSSFWorkbook(), TempFile.createTempFile("rotated", ".xlsx"));
  2448. }
  2449. @Test
  2450. public void test59132() throws IOException {
  2451. Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("59132.xlsx");
  2452. Sheet worksheet = workbook.getSheet("sheet1");
  2453. // B3
  2454. Row row = worksheet.getRow(2);
  2455. Cell cell = row.getCell(1);
  2456. cell.setCellValue((String) null);
  2457. FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
  2458. // B3
  2459. row = worksheet.getRow(2);
  2460. cell = row.getCell(1);
  2461. assertEquals(CellType.BLANK, cell.getCellType());
  2462. assertEquals(CellType._NONE, evaluator.evaluateFormulaCell(cell));
  2463. // A3
  2464. row = worksheet.getRow(2);
  2465. cell = row.getCell(0);
  2466. assertEquals(CellType.FORMULA, cell.getCellType());
  2467. assertEquals("IF(ISBLANK(B3),\"\",B3)", cell.getCellFormula());
  2468. assertEquals(CellType.STRING, evaluator.evaluateFormulaCell(cell));
  2469. CellValue value = evaluator.evaluate(cell);
  2470. assertEquals("", value.getStringValue());
  2471. // A5
  2472. row = worksheet.getRow(4);
  2473. cell = row.getCell(0);
  2474. assertEquals(CellType.FORMULA, cell.getCellType());
  2475. assertEquals("COUNTBLANK(A1:A4)", cell.getCellFormula());
  2476. assertEquals(CellType.NUMERIC, evaluator.evaluateFormulaCell(cell));
  2477. value = evaluator.evaluate(cell);
  2478. assertEquals(1.0, value.getNumberValue(), 0.1);
  2479. /*FileOutputStream output = new FileOutputStream("C:\\temp\\59132.xlsx");
  2480. try {
  2481. workbook.write(output);
  2482. } finally {
  2483. output.close();
  2484. }*/
  2485. workbook.close();
  2486. }
  2487. @Ignore("bug 59442")
  2488. @Test
  2489. public void testSetRGBBackgroundColor() throws IOException {
  2490. XSSFWorkbook workbook = new XSSFWorkbook();
  2491. XSSFCell cell = workbook.createSheet().createRow(0).createCell(0);
  2492. XSSFColor color = new XSSFColor(java.awt.Color.RED, workbook.getStylesSource().getIndexedColors());
  2493. XSSFCellStyle style = workbook.createCellStyle();
  2494. style.setFillForegroundColor(color);
  2495. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  2496. cell.setCellStyle(style);
  2497. // Everything is fine at this point, cell is red
  2498. XSSFColor actual = cell.getCellStyle().getFillBackgroundColorColor();
  2499. assertNull(actual);
  2500. actual = cell.getCellStyle().getFillForegroundColorColor();
  2501. assertNotNull(actual);
  2502. assertEquals(color.getARGBHex(), actual.getARGBHex());
  2503. Map<String, Object> properties = new HashMap<>();
  2504. properties.put(CellUtil.BORDER_BOTTOM, BorderStyle.THIN);
  2505. CellUtil.setCellStyleProperties(cell, properties);
  2506. // Now the cell is all black
  2507. actual = cell.getCellStyle().getFillBackgroundColorColor();
  2508. assertNotNull(actual);
  2509. assertNull(actual.getARGBHex());
  2510. actual = cell.getCellStyle().getFillForegroundColorColor();
  2511. assertNotNull(actual);
  2512. assertEquals(color.getARGBHex(), actual.getARGBHex());
  2513. XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(workbook);
  2514. workbook.close();
  2515. XSSFCell ncell = nwb.getSheetAt(0).getRow(0).getCell(0);
  2516. XSSFColor ncolor = new XSSFColor(java.awt.Color.RED, workbook.getStylesSource().getIndexedColors());
  2517. // Now the cell is all black
  2518. XSSFColor nactual = ncell.getCellStyle().getFillBackgroundColorColor();
  2519. assertNotNull(nactual);
  2520. assertEquals(ncolor.getARGBHex(), nactual.getARGBHex());
  2521. nwb.close();
  2522. }
  2523. @Ignore("currently fails on POI 3.15 beta 2")
  2524. @Test
  2525. public void test55273() throws IOException {
  2526. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("ExcelTables.xlsx")) {
  2527. Sheet sheet = wb.getSheet("ExcelTable");
  2528. Name name = wb.getName("TableAsRangeName");
  2529. assertEquals("TableName[#All]", name.getRefersToFormula());
  2530. // POI 3.15-beta 2 (2016-06-15): getSheetName throws IllegalArgumentException: Invalid CellReference: TableName[#All]
  2531. assertEquals("TableName", name.getSheetName());
  2532. XSSFSheet xsheet = (XSSFSheet) sheet;
  2533. List<XSSFTable> tables = xsheet.getTables();
  2534. assertEquals(2, tables.size()); //FIXME: how many tables are there in this spreadsheet?
  2535. assertEquals("Table1", tables.get(0).getName()); //FIXME: what is the table name?
  2536. assertEquals("Table2", tables.get(1).getName()); //FIXME: what is the table name?
  2537. }
  2538. }
  2539. @Test
  2540. public void test57523() throws IOException {
  2541. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57523.xlsx")) {
  2542. Sheet sheet = wb.getSheet("Attribute Master");
  2543. Row row = sheet.getRow(15);
  2544. int N = CellReference.convertColStringToIndex("N");
  2545. Cell N16 = row.getCell(N);
  2546. assertEquals(500.0, N16.getNumericCellValue(), 0.00001);
  2547. int P = CellReference.convertColStringToIndex("P");
  2548. Cell P16 = row.getCell(P);
  2549. assertEquals(10.0, P16.getNumericCellValue(), 0.00001);
  2550. }
  2551. }
  2552. /**
  2553. * Files produced by some scientific equipment neglect
  2554. * to include the row number on the row tags
  2555. */
  2556. @Test
  2557. public void noRowNumbers59746() throws IOException {
  2558. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("59746_NoRowNums.xlsx")) {
  2559. Sheet sheet = wb.getSheetAt(0);
  2560. assertTrue("Last row num: " + sheet.getLastRowNum(), sheet.getLastRowNum() > 20);
  2561. assertEquals("Checked", sheet.getRow(0).getCell(0).getStringCellValue());
  2562. assertEquals("Checked", sheet.getRow(9).getCell(2).getStringCellValue());
  2563. assertFalse(sheet.getRow(70).getCell(8).getBooleanCellValue());
  2564. assertEquals(71, sheet.getPhysicalNumberOfRows());
  2565. assertEquals(70, sheet.getLastRowNum());
  2566. assertEquals(70, sheet.getRow(sheet.getLastRowNum()).getRowNum());
  2567. }
  2568. }
  2569. @Test
  2570. public void testWorkdayFunction() throws IOException {
  2571. try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("59106.xlsx")) {
  2572. XSSFSheet sheet = workbook.getSheet("Test");
  2573. Row row = sheet.getRow(1);
  2574. Cell cell = row.getCell(0);
  2575. DataFormatter form = new DataFormatter();
  2576. FormulaEvaluator evaluator = cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
  2577. String result = form.formatCellValue(cell, evaluator);
  2578. assertEquals("09 Mar 2016", result);
  2579. }
  2580. }
  2581. // This bug is currently open. When this bug is fixed, it should not throw an AssertionError
  2582. @Test(expected = AssertionError.class)
  2583. public void test55076_collapseColumnGroups() throws Exception {
  2584. Workbook wb = new XSSFWorkbook();
  2585. Sheet sheet = wb.createSheet();
  2586. // this column collapsing bug only occurs when the grouped columns are different widths
  2587. sheet.setColumnWidth(1, 400);
  2588. sheet.setColumnWidth(2, 600);
  2589. sheet.setColumnWidth(3, 800);
  2590. assertEquals(400, sheet.getColumnWidth(1));
  2591. assertEquals(600, sheet.getColumnWidth(2));
  2592. assertEquals(800, sheet.getColumnWidth(3));
  2593. sheet.groupColumn(1, 3);
  2594. sheet.setColumnGroupCollapsed(1, true);
  2595. assertEquals(0, sheet.getColumnOutlineLevel(0));
  2596. assertEquals(1, sheet.getColumnOutlineLevel(1));
  2597. assertEquals(1, sheet.getColumnOutlineLevel(2));
  2598. assertEquals(1, sheet.getColumnOutlineLevel(3));
  2599. assertEquals(0, sheet.getColumnOutlineLevel(4));
  2600. // none of the columns should be hidden
  2601. // column group collapsing is a different concept
  2602. for (int c = 0; c < 5; c++) {
  2603. assertFalse("Column " + c, sheet.isColumnHidden(c));
  2604. }
  2605. assertEquals(400, sheet.getColumnWidth(1));
  2606. assertEquals(600, sheet.getColumnWidth(2));
  2607. assertEquals(800, sheet.getColumnWidth(3));
  2608. wb.close();
  2609. }
  2610. /**
  2611. * Other things, including charts, may end up taking drawing part
  2612. * numbers. (Uses a test file hand-crafted with an extra non-drawing
  2613. * part with a part number)
  2614. */
  2615. @Test
  2616. public void drawingNumbersAlreadyTaken_60255() throws IOException {
  2617. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("60255_extra_drawingparts.xlsx")) {
  2618. assertEquals(4, wb.getNumberOfSheets());
  2619. // Sheet 3 starts with a drawing
  2620. Sheet sheet = wb.getSheetAt(0);
  2621. assertNull(sheet.getDrawingPatriarch());
  2622. sheet = wb.getSheetAt(1);
  2623. assertNull(sheet.getDrawingPatriarch());
  2624. sheet = wb.getSheetAt(2);
  2625. assertNotNull(sheet.getDrawingPatriarch());
  2626. sheet = wb.getSheetAt(3);
  2627. assertNull(sheet.getDrawingPatriarch());
  2628. // Add another sheet, and give it a drawing
  2629. sheet = wb.createSheet();
  2630. assertNull(sheet.getDrawingPatriarch());
  2631. sheet.createDrawingPatriarch();
  2632. assertNotNull(sheet.getDrawingPatriarch());
  2633. // Save and check
  2634. Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  2635. assertEquals(5, wbBack.getNumberOfSheets());
  2636. // Sheets 3 and 5 now
  2637. sheet = wbBack.getSheetAt(0);
  2638. assertNull(sheet.getDrawingPatriarch());
  2639. sheet = wbBack.getSheetAt(1);
  2640. assertNull(sheet.getDrawingPatriarch());
  2641. sheet = wbBack.getSheetAt(2);
  2642. assertNotNull(sheet.getDrawingPatriarch());
  2643. sheet = wbBack.getSheetAt(3);
  2644. assertNull(sheet.getDrawingPatriarch());
  2645. sheet = wbBack.getSheetAt(4);
  2646. assertNotNull(sheet.getDrawingPatriarch());
  2647. }
  2648. }
  2649. @Test
  2650. public void test53611() throws IOException {
  2651. Workbook wb = new XSSFWorkbook();
  2652. Sheet sheet = wb.createSheet("test");
  2653. Row row = sheet.createRow(1);
  2654. Cell cell = row.createCell(1);
  2655. cell.setCellValue("blabla");
  2656. //0 1 2 3 4 5 6 7
  2657. //A B C D E F G H
  2658. row = sheet.createRow(4);
  2659. cell = row.createCell(7);
  2660. cell.setCellValue("blabla");
  2661. // we currently only populate the dimension during writing out
  2662. // to avoid having to iterate all rows/cells in each add/remove of a row or cell
  2663. wb.write(new NullOutputStream());
  2664. assertEquals("B2:H5", ((XSSFSheet) sheet).getCTWorksheet().getDimension().getRef());
  2665. wb.close();
  2666. }
  2667. @Test
  2668. public void test61798() throws IOException {
  2669. Workbook wb = new XSSFWorkbook();
  2670. Sheet sheet = wb.createSheet("test");
  2671. Row row = sheet.createRow(1);
  2672. Cell cell = row.createCell(1);
  2673. cell.setCellValue("blabla");
  2674. row = sheet.createRow(4);
  2675. // Allowable column range for EXCEL2007 is (0..16383) or ('A'..'XDF')
  2676. cell = row.createCell(16383);
  2677. cell.setCellValue("blabla");
  2678. // we currently only populate the dimension during writing out
  2679. // to avoid having to iterate all rows/cells in each add/remove of a row or cell
  2680. wb.write(new NullOutputStream());
  2681. assertEquals("B2:XFD5", ((XSSFSheet)sheet).getCTWorksheet().getDimension().getRef());
  2682. wb.close();
  2683. }
  2684. @Test
  2685. public void bug61063() throws Exception {
  2686. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("61063.xlsx")) {
  2687. FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator();
  2688. Sheet s = wb.getSheetAt(0);
  2689. Row r = s.getRow(3);
  2690. Cell c = r.getCell(0);
  2691. assertEquals(CellType.FORMULA, c.getCellType());
  2692. eval.setDebugEvaluationOutputForNextEval(true);
  2693. CellValue cv = eval.evaluate(c);
  2694. assertNotNull(cv);
  2695. assertEquals("Had: " + cv, 2.0, cv.getNumberValue(), 0.00001);
  2696. }
  2697. }
  2698. @Test
  2699. public void bug61516() throws IOException {
  2700. final String initialFormula = "A1";
  2701. final String expectedFormula = "#REF!"; // from ms excel
  2702. XSSFWorkbook wb = new XSSFWorkbook();
  2703. Sheet sheet = wb.createSheet("sheet1");
  2704. sheet.createRow(0).createCell(0).setCellValue(1); // A1 = 1
  2705. {
  2706. Cell c3 = sheet.createRow(2).createCell(2);
  2707. c3.setCellFormula(initialFormula); // C3 = =A1
  2708. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  2709. CellValue cellValue = evaluator.evaluate(c3);
  2710. assertEquals(1, cellValue.getNumberValue(), 0.0001);
  2711. }
  2712. {
  2713. FormulaShifter formulaShifter = FormulaShifter.createForRowCopy(0, "sheet1", 2/*firstRowToShift*/, 2/*lastRowToShift*/
  2714. , -1/*step*/, SpreadsheetVersion.EXCEL2007); // parameters 2, 2, -1 should mean : move row range [2-2] one level up
  2715. XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb);
  2716. Ptg[] ptgs = FormulaParser.parse(initialFormula, fpb, FormulaType.CELL, 0); // [A1]
  2717. formulaShifter.adjustFormula(ptgs, 0); // adjusted to [A]
  2718. String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs); //A
  2719. //System.out.println(String.format("initial formula : A1; expected formula value after shifting up : #REF!; actual formula value : %s", shiftedFmla));
  2720. assertEquals("On copy we expect the formula to be adjusted, in this case it would point to row -1, which is an invalid REF",
  2721. expectedFormula, shiftedFmla);
  2722. }
  2723. {
  2724. FormulaShifter formulaShifter = FormulaShifter.createForRowShift(0, "sheet1", 2/*firstRowToShift*/, 2/*lastRowToShift*/
  2725. , -1/*step*/, SpreadsheetVersion.EXCEL2007); // parameters 2, 2, -1 should mean : move row range [2-2] one level up
  2726. XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb);
  2727. Ptg[] ptgs = FormulaParser.parse(initialFormula, fpb, FormulaType.CELL, 0); // [A1]
  2728. formulaShifter.adjustFormula(ptgs, 0); // adjusted to [A]
  2729. String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs); //A
  2730. //System.out.println(String.format("initial formula : A1; expected formula value after shifting up : #REF!; actual formula value : %s", shiftedFmla));
  2731. assertEquals("On move we expect the formula to stay the same, thus expecting the initial formula A1 here",
  2732. initialFormula, shiftedFmla);
  2733. }
  2734. sheet.shiftRows(2, 2, -1);
  2735. {
  2736. Cell c2 = sheet.getRow(1).getCell(2);
  2737. assertNotNull("cell C2 needs to exist now", c2);
  2738. assertEquals(CellType.FORMULA, c2.getCellType());
  2739. assertEquals(initialFormula, c2.getCellFormula());
  2740. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  2741. CellValue cellValue = evaluator.evaluate(c2);
  2742. assertEquals(1, cellValue.getNumberValue(), 0.0001);
  2743. }
  2744. wb.close();
  2745. }
  2746. @Test
  2747. public void test61652() throws IOException {
  2748. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("61652.xlsx")) {
  2749. Sheet sheet = wb.getSheet("IRPPCalc");
  2750. Row row = sheet.getRow(11);
  2751. Cell cell = row.getCell(18);
  2752. WorkbookEvaluatorProvider fe = (WorkbookEvaluatorProvider) wb.getCreationHelper().createFormulaEvaluator();
  2753. ConditionalFormattingEvaluator condfmt = new ConditionalFormattingEvaluator(wb, fe);
  2754. assertEquals("Conditional formatting is not triggered for this cell",
  2755. "[]", condfmt.getConditionalFormattingForCell(cell).toString());
  2756. // but we can read the conditional formatting itself
  2757. List<EvaluationConditionalFormatRule> rules = condfmt.getFormatRulesForSheet(sheet);
  2758. assertEquals(1, rules.size());
  2759. assertEquals("AND($A1>=EDATE($D$6,3),$B1>0)", rules.get(0).getFormula1());
  2760. }
  2761. }
  2762. @Test
  2763. public void test61543() throws IOException {
  2764. try (XSSFWorkbook wb = new XSSFWorkbook()) {
  2765. XSSFSheet sheet = wb.createSheet();
  2766. XSSFTable table1 = sheet.createTable(null);
  2767. XSSFTable table2 = sheet.createTable(null);
  2768. XSSFTable table3 = sheet.createTable(null);
  2769. sheet.removeTable(table1);
  2770. sheet.createTable(null);
  2771. sheet.removeTable(table2);
  2772. sheet.removeTable(table3);
  2773. sheet.createTable(null);
  2774. }
  2775. }
  2776. /**
  2777. * Auto column sizing failed when there were loads of fonts with
  2778. * errors like ArrayIndexOutOfBoundsException: -32765
  2779. */
  2780. @Test
  2781. public void test62108() throws IOException {
  2782. try (XSSFWorkbook wb = new XSSFWorkbook()) {
  2783. XSSFSheet sheet = wb.createSheet();
  2784. XSSFRow row = sheet.createRow(0);
  2785. // Create lots of fonts
  2786. XSSFDataFormat formats = wb.createDataFormat();
  2787. XSSFFont[] fonts = new XSSFFont[50000];
  2788. for (int i = 0; i < fonts.length; i++) {
  2789. XSSFFont font = wb.createFont();
  2790. font.setFontHeight(i);
  2791. fonts[i] = font;
  2792. }
  2793. // Create a moderate number of columns, which use
  2794. // fonts from the start and end of the font list
  2795. final int numCols = 125;
  2796. for (int i = 0; i < numCols; i++) {
  2797. XSSFCellStyle cs = wb.createCellStyle();
  2798. cs.setDataFormat(formats.getFormat("'Test " + i + "' #,###"));
  2799. XSSFFont font = fonts[i];
  2800. if (i % 2 == 1) {
  2801. font = fonts[fonts.length - i];
  2802. }
  2803. cs.setFont(font);
  2804. XSSFCell c = row.createCell(i);
  2805. c.setCellValue(i);
  2806. c.setCellStyle(cs);
  2807. }
  2808. // Do the auto-size
  2809. for (int i = 0; i < numCols; i++) {
  2810. sheet.autoSizeColumn(i);
  2811. }
  2812. }
  2813. }
  2814. @Test
  2815. public void test61905xlsx() throws IOException {
  2816. try (Workbook wb = new XSSFWorkbook()) {
  2817. checkActiveSheet(wb, XSSFITestDataProvider.instance);
  2818. }
  2819. }
  2820. @Test
  2821. public void test61905xls() throws IOException {
  2822. try (Workbook wb = new HSSFWorkbook()) {
  2823. checkActiveSheet(wb, HSSFITestDataProvider.instance);
  2824. }
  2825. }
  2826. private void checkActiveSheet(Workbook wb, ITestDataProvider instance) throws IOException {
  2827. Sheet sheet = wb.createSheet("new sheet");
  2828. sheet.setActiveCell(new CellAddress("E11"));
  2829. assertEquals("E11", sheet.getActiveCell().formatAsString());
  2830. Workbook wbBack = instance.writeOutAndReadBack(wb);
  2831. sheet = wbBack.getSheetAt(0);
  2832. assertEquals("E11", sheet.getActiveCell().formatAsString());
  2833. wbBack.close();
  2834. }
  2835. @Test
  2836. public void testBug54084Unicode() throws IOException {
  2837. // sample XLSX with the same text-contents as the text-file above
  2838. try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("54084 - Greek - beyond BMP.xlsx")) {
  2839. verifyBug54084Unicode(wb);
  2840. //XSSFTestDataSamples.writeOut(wb, "bug 54084 for manual review");
  2841. // now write the file and read it back in
  2842. XSSFWorkbook wbWritten = XSSFTestDataSamples.writeOutAndReadBack(wb);
  2843. verifyBug54084Unicode(wbWritten);
  2844. // finally also write it out via the streaming interface and verify that we still can read it back in
  2845. SXSSFWorkbook swb = new SXSSFWorkbook(wb);
  2846. Workbook wbStreamingWritten = SXSSFITestDataProvider.instance.writeOutAndReadBack(swb);
  2847. verifyBug54084Unicode(wbStreamingWritten);
  2848. wbWritten.close();
  2849. swb.close();
  2850. wbStreamingWritten.close();
  2851. }
  2852. }
  2853. private void verifyBug54084Unicode(Workbook wb) {
  2854. // expected data is stored in UTF-8 in a text-file
  2855. byte[] data = HSSFTestDataSamples.getTestDataFileContent("54084 - Greek - beyond BMP.txt");
  2856. String testData = new String(data, StandardCharsets.UTF_8).trim();
  2857. Sheet sheet = wb.getSheetAt(0);
  2858. Row row = sheet.getRow(0);
  2859. Cell cell = row.getCell(0);
  2860. String value = cell.getStringCellValue();
  2861. //System.out.println(value);
  2862. assertEquals("The data in the text-file should exactly match the data that we read from the workbook", testData, value);
  2863. }
  2864. @Test
  2865. public void bug63371() throws IOException {
  2866. try (XSSFWorkbook wb = new XSSFWorkbook()) {
  2867. XSSFSheet sheet = wb.createSheet();
  2868. CellRangeAddress region = new CellRangeAddress(1, 1, 1, 2);
  2869. assertEquals(0, sheet.addMergedRegion(region));
  2870. //System.out.println(String.format("%s: index=%d", "testAddMergedRegion", index));
  2871. final List<CellRangeAddress> ranges = sheet.getMergedRegions();
  2872. final int numMergedRegions = sheet.getNumMergedRegions();
  2873. final CTWorksheet ctSheet = sheet.getCTWorksheet();
  2874. final CTMergeCells ctMergeCells = ctSheet.getMergeCells();
  2875. final List<CTMergeCell> ctMergeCellList = ctMergeCells.getMergeCellList();
  2876. final long ctMergeCellCount = ctMergeCells.getCount();
  2877. final int ctMergeCellListSize = ctMergeCellList.size();
  2878. /*System.out.println(String.format("\ntestMergeRegions(%s)", "After adding first region"));
  2879. System.out.println(String.format("ranges.size=%d", ranges.size()));
  2880. System.out.println(String.format("numMergedRegions=%d", numMergedRegions));
  2881. System.out.println(String.format("ctMergeCellCount=%d", ctMergeCellCount));
  2882. System.out.println(String.format("ctMergeCellListSize=%d", ctMergeCellListSize));*/
  2883. assertEquals(1, ranges.size());
  2884. assertEquals(1, numMergedRegions);
  2885. assertEquals(1, ctMergeCellCount);
  2886. assertEquals(1, ctMergeCellListSize);
  2887. }
  2888. }
  2889. @Test
  2890. public void testBug63509() throws IOException {
  2891. try (XSSFWorkbook workbook = new XSSFWorkbook()) {
  2892. XSSFSheet sheet = workbook.createSheet("sheet1");
  2893. Row row = sheet.createRow(0);
  2894. Cell cell = row.createCell(0);
  2895. cell.setCellValue("1000");
  2896. // This causes the error
  2897. sheet.addIgnoredErrors(new CellReference(cell), IgnoredErrorType.NUMBER_STORED_AS_TEXT);
  2898. // Workaround
  2899. // sheet.addIgnoredErrors(new CellReference(cell.getRowIndex(), cell.getColumnIndex(), false, false),
  2900. // IgnoredErrorType.NUMBER_STORED_AS_TEXT);
  2901. /*File file = new File("/tmp/63509.xlsx");
  2902. try(FileOutputStream outputStream = new FileOutputStream(file)) {
  2903. workbook.write(outputStream);
  2904. }*/
  2905. }
  2906. }
  2907. @Test(expected = POIXMLException.class)
  2908. public void test64045() throws IOException, InvalidFormatException {
  2909. File file = XSSFTestDataSamples.getSampleFile("xlsx-corrupted.xlsx");
  2910. try (XSSFWorkbook ignored = new XSSFWorkbook(file)) {
  2911. fail("Should catch exception as the file is corrupted");
  2912. }
  2913. }
  2914. @Test
  2915. public void test58896WithFile() throws IOException {
  2916. try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58896.xlsx")) {
  2917. Sheet sheet = wb.getSheetAt(0);
  2918. Instant start = Instant.now();
  2919. LOG.log(POILogger.INFO, "Autosizing columns...");
  2920. for (int i = 0; i < 3; ++i) {
  2921. LOG.log(POILogger.INFO, "Autosize " + i + " - " + Duration.between(start, Instant.now()));
  2922. sheet.autoSizeColumn(i);
  2923. }
  2924. for (int i = 0; i < 69 - 35 + 1; ++i)
  2925. for (int j = 0; j < 8; ++j) {
  2926. int col = 3 + 2 + i * (8 + 2) + j;
  2927. LOG.log(POILogger.INFO, "Autosize " + col + " - " + Duration.between(start, Instant.now()));
  2928. sheet.autoSizeColumn(col);
  2929. }
  2930. LOG.log(POILogger.INFO, Duration.between(start, Instant.now()));
  2931. }
  2932. }
  2933. }