You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TestXSSFBugs.java 157KB

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