Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

TestXSSFBugs.java 141KB

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