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

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