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

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