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

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