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

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