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

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