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.

XSSFSheet.java 176KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.xssf.usermodel;
  16. import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
  17. import static org.apache.poi.xssf.usermodel.helpers.XSSFPasswordHelper.setPassword;
  18. import static org.apache.poi.xssf.usermodel.helpers.XSSFPasswordHelper.validatePassword;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.OutputStream;
  22. import java.util.ArrayList;
  23. import java.util.Collection;
  24. import java.util.Collections;
  25. import java.util.HashMap;
  26. import java.util.Iterator;
  27. import java.util.LinkedHashMap;
  28. import java.util.LinkedHashSet;
  29. import java.util.List;
  30. import java.util.Map;
  31. import java.util.Set;
  32. import java.util.SortedMap;
  33. import java.util.TreeMap;
  34. import javax.xml.namespace.QName;
  35. import javax.xml.stream.XMLStreamException;
  36. import javax.xml.stream.XMLStreamReader;
  37. import org.apache.poi.ooxml.POIXMLDocumentPart;
  38. import org.apache.poi.ooxml.POIXMLException;
  39. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  40. import org.apache.poi.openxml4j.exceptions.PartAlreadyExistsException;
  41. import org.apache.poi.openxml4j.opc.PackagePart;
  42. import org.apache.poi.openxml4j.opc.PackageRelationship;
  43. import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
  44. import org.apache.poi.openxml4j.opc.TargetMode;
  45. import org.apache.poi.poifs.crypt.HashAlgorithm;
  46. import org.apache.poi.ss.SpreadsheetVersion;
  47. import org.apache.poi.ss.formula.FormulaShifter;
  48. import org.apache.poi.ss.formula.SheetNameFormatter;
  49. import org.apache.poi.ss.usermodel.Cell;
  50. import org.apache.poi.ss.usermodel.CellCopyPolicy;
  51. import org.apache.poi.ss.usermodel.CellRange;
  52. import org.apache.poi.ss.usermodel.CellStyle;
  53. import org.apache.poi.ss.usermodel.CellType;
  54. import org.apache.poi.ss.usermodel.DataValidation;
  55. import org.apache.poi.ss.usermodel.DataValidationHelper;
  56. import org.apache.poi.ss.usermodel.Font;
  57. import org.apache.poi.ss.usermodel.Footer;
  58. import org.apache.poi.ss.usermodel.Header;
  59. import org.apache.poi.ss.usermodel.IgnoredErrorType;
  60. import org.apache.poi.ss.usermodel.Name;
  61. import org.apache.poi.ss.usermodel.Row;
  62. import org.apache.poi.ss.usermodel.Sheet;
  63. import org.apache.poi.ss.usermodel.Table;
  64. import org.apache.poi.ss.util.AreaReference;
  65. import org.apache.poi.ss.util.CellAddress;
  66. import org.apache.poi.ss.util.CellRangeAddress;
  67. import org.apache.poi.ss.util.CellRangeAddressList;
  68. import org.apache.poi.ss.util.CellReference;
  69. import org.apache.poi.ss.util.PaneInformation;
  70. import org.apache.poi.ss.util.SSCellRange;
  71. import org.apache.poi.ss.util.SheetUtil;
  72. import org.apache.poi.util.Beta;
  73. import org.apache.poi.util.Internal;
  74. import org.apache.poi.util.POILogFactory;
  75. import org.apache.poi.util.POILogger;
  76. import org.apache.poi.util.Units;
  77. import org.apache.poi.xssf.model.CommentsTable;
  78. import org.apache.poi.xssf.usermodel.XSSFPivotTable.PivotTableReferenceConfigurator;
  79. import org.apache.poi.xssf.usermodel.helpers.ColumnHelper;
  80. import org.apache.poi.xssf.usermodel.helpers.XSSFColumnShifter;
  81. import org.apache.poi.xssf.usermodel.helpers.XSSFIgnoredErrorHelper;
  82. import org.apache.poi.xssf.usermodel.helpers.XSSFRowShifter;
  83. import org.apache.xmlbeans.XmlCursor;
  84. import org.apache.xmlbeans.XmlException;
  85. import org.apache.xmlbeans.XmlObject;
  86. import org.apache.xmlbeans.XmlOptions;
  87. import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
  88. /**
  89. * High level representation of a SpreadsheetML worksheet.
  90. *
  91. * <p>
  92. * Sheets are the central structures within a workbook, and are where a user does most of his spreadsheet work.
  93. * The most common type of sheet is the worksheet, which is represented as a grid of cells. Worksheet cells can
  94. * contain text, numbers, dates, and formulas. Cells can also be formatted.
  95. * </p>
  96. */
  97. public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
  98. private static final POILogger logger = POILogFactory.getLogger(XSSFSheet.class);
  99. private static final double DEFAULT_ROW_HEIGHT = 15.0;
  100. private static final double DEFAULT_MARGIN_HEADER = 0.3;
  101. private static final double DEFAULT_MARGIN_FOOTER = 0.3;
  102. private static final double DEFAULT_MARGIN_TOP = 0.75;
  103. private static final double DEFAULT_MARGIN_BOTTOM = 0.75;
  104. private static final double DEFAULT_MARGIN_LEFT = 0.7;
  105. private static final double DEFAULT_MARGIN_RIGHT = 0.7;
  106. /**
  107. * Kept for backwards-compatibility, use {@link Font#TWIPS_PER_POINT} instead.
  108. * @deprecated POI 5.0.0
  109. */
  110. public static final int TWIPS_PER_POINT = Font.TWIPS_PER_POINT;
  111. //TODO make the two variable below private!
  112. protected CTSheet sheet;
  113. protected CTWorksheet worksheet;
  114. private final SortedMap<Integer, XSSFRow> _rows = new TreeMap<>();
  115. private List<XSSFHyperlink> hyperlinks;
  116. private ColumnHelper columnHelper;
  117. private CommentsTable sheetComments;
  118. /**
  119. * cache of master shared formulas in this sheet.
  120. * Master shared formula is the first formula in a group of shared formulas is saved in the f element.
  121. */
  122. private Map<Integer, CTCellFormula> sharedFormulas;
  123. private SortedMap<String,XSSFTable> tables;
  124. private List<CellRangeAddress> arrayFormulas;
  125. private final XSSFDataValidationHelper dataValidationHelper;
  126. /**
  127. * Creates new XSSFSheet - called by XSSFWorkbook to create a sheet from scratch.
  128. *
  129. * @see org.apache.poi.xssf.usermodel.XSSFWorkbook#createSheet()
  130. */
  131. protected XSSFSheet() {
  132. super();
  133. dataValidationHelper = new XSSFDataValidationHelper(this);
  134. onDocumentCreate();
  135. }
  136. /**
  137. * Creates an XSSFSheet representing the given package part and relationship.
  138. * Should only be called by XSSFWorkbook when reading in an existing file.
  139. *
  140. * @param part - The package part that holds xml data representing this sheet.
  141. *
  142. * @since POI 3.14-Beta1
  143. */
  144. protected XSSFSheet(PackagePart part) {
  145. super(part);
  146. dataValidationHelper = new XSSFDataValidationHelper(this);
  147. }
  148. /**
  149. * Returns the parent XSSFWorkbook
  150. *
  151. * @return the parent XSSFWorkbook
  152. */
  153. @Override
  154. public XSSFWorkbook getWorkbook() {
  155. return (XSSFWorkbook)getParent();
  156. }
  157. /**
  158. * Initialize worksheet data when reading in an exisiting file.
  159. */
  160. @Override
  161. protected void onDocumentRead() {
  162. try {
  163. read(getPackagePart().getInputStream());
  164. } catch (IOException e){
  165. throw new POIXMLException(e);
  166. }
  167. }
  168. protected void read(InputStream is) throws IOException {
  169. try {
  170. worksheet = WorksheetDocument.Factory.parse(is, DEFAULT_XML_OPTIONS).getWorksheet();
  171. } catch (XmlException e){
  172. throw new POIXMLException(e);
  173. }
  174. initRows(worksheet);
  175. columnHelper = new ColumnHelper(worksheet);
  176. // Look for bits we're interested in
  177. for(RelationPart rp : getRelationParts()){
  178. POIXMLDocumentPart p = rp.getDocumentPart();
  179. if(p instanceof CommentsTable) {
  180. sheetComments = (CommentsTable)p;
  181. }
  182. if(p instanceof XSSFTable) {
  183. tables.put( rp.getRelationship().getId(), (XSSFTable)p );
  184. }
  185. if(p instanceof XSSFPivotTable) {
  186. getWorkbook().getPivotTables().add((XSSFPivotTable) p);
  187. }
  188. }
  189. // Process external hyperlinks for the sheet, if there are any
  190. initHyperlinks();
  191. }
  192. /**
  193. * Initialize worksheet data when creating a new sheet.
  194. */
  195. @Override
  196. protected void onDocumentCreate(){
  197. worksheet = newSheet();
  198. initRows(worksheet);
  199. columnHelper = new ColumnHelper(worksheet);
  200. hyperlinks = new ArrayList<>();
  201. }
  202. private void initRows(CTWorksheet worksheetParam) {
  203. _rows.clear();
  204. tables = new TreeMap<>();
  205. sharedFormulas = new HashMap<>();
  206. arrayFormulas = new ArrayList<>();
  207. for (CTRow row : worksheetParam.getSheetData().getRowArray()) {
  208. XSSFRow r = new XSSFRow(row, this);
  209. // Performance optimization: explicit boxing is slightly faster than auto-unboxing, though may use more memory
  210. //noinspection UnnecessaryBoxing
  211. final Integer rownumI = Integer.valueOf(r.getRowNum()); // NOSONAR
  212. _rows.put(rownumI, r);
  213. }
  214. }
  215. /**
  216. * Read hyperlink relations, link them with CTHyperlink beans in this worksheet
  217. * and initialize the internal array of XSSFHyperlink objects
  218. */
  219. private void initHyperlinks() {
  220. hyperlinks = new ArrayList<>();
  221. if(!worksheet.isSetHyperlinks()) {
  222. return;
  223. }
  224. try {
  225. PackageRelationshipCollection hyperRels =
  226. getPackagePart().getRelationshipsByType(XSSFRelation.SHEET_HYPERLINKS.getRelation());
  227. // Turn each one into a XSSFHyperlink
  228. for(CTHyperlink hyperlink : worksheet.getHyperlinks().getHyperlinkArray()) {
  229. PackageRelationship hyperRel = null;
  230. if(hyperlink.getId() != null) {
  231. hyperRel = hyperRels.getRelationshipByID(hyperlink.getId());
  232. }
  233. hyperlinks.add( new XSSFHyperlink(hyperlink, hyperRel) );
  234. }
  235. } catch (InvalidFormatException e){
  236. throw new POIXMLException(e);
  237. }
  238. }
  239. /**
  240. * Create a new CTWorksheet instance with all values set to defaults
  241. *
  242. * @return a new instance
  243. */
  244. private static CTWorksheet newSheet(){
  245. CTWorksheet worksheet = CTWorksheet.Factory.newInstance();
  246. CTSheetFormatPr ctFormat = worksheet.addNewSheetFormatPr();
  247. ctFormat.setDefaultRowHeight(DEFAULT_ROW_HEIGHT);
  248. CTSheetView ctView = worksheet.addNewSheetViews().addNewSheetView();
  249. ctView.setWorkbookViewId(0);
  250. worksheet.addNewDimension().setRef("A1");
  251. worksheet.addNewSheetData();
  252. CTPageMargins ctMargins = worksheet.addNewPageMargins();
  253. ctMargins.setBottom(DEFAULT_MARGIN_BOTTOM);
  254. ctMargins.setFooter(DEFAULT_MARGIN_FOOTER);
  255. ctMargins.setHeader(DEFAULT_MARGIN_HEADER);
  256. ctMargins.setLeft(DEFAULT_MARGIN_LEFT);
  257. ctMargins.setRight(DEFAULT_MARGIN_RIGHT);
  258. ctMargins.setTop(DEFAULT_MARGIN_TOP);
  259. return worksheet;
  260. }
  261. /**
  262. * Provide access to the CTWorksheet bean holding this sheet's data
  263. *
  264. * @return the CTWorksheet bean holding this sheet's data
  265. */
  266. @Internal
  267. public CTWorksheet getCTWorksheet() {
  268. return this.worksheet;
  269. }
  270. public ColumnHelper getColumnHelper() {
  271. return columnHelper;
  272. }
  273. /**
  274. * Returns the name of this sheet
  275. *
  276. * @return the name of this sheet
  277. */
  278. @Override
  279. public String getSheetName() {
  280. return sheet.getName();
  281. }
  282. /**
  283. * Adds a merged region of cells on a sheet.
  284. *
  285. * @param region to merge
  286. * @return index of this region
  287. * @throws IllegalArgumentException if region contains fewer than 2 cells
  288. * @throws IllegalStateException if region intersects with a multi-cell array formula
  289. * @throws IllegalStateException if region intersects with an existing region on this sheet
  290. */
  291. @Override
  292. public int addMergedRegion(CellRangeAddress region) {
  293. return addMergedRegion(region, true);
  294. }
  295. /**
  296. * Adds a merged region of cells (hence those cells form one).
  297. * Skips validation. It is possible to create overlapping merged regions
  298. * or create a merged region that intersects a multi-cell array formula
  299. * with this formula, which may result in a corrupt workbook.
  300. *
  301. * To check for merged regions overlapping array formulas or other merged regions
  302. * after addMergedRegionUnsafe has been called, call {@link #validateMergedRegions()}, which runs in O(n^2) time.
  303. *
  304. * @param region to merge
  305. * @return index of this region
  306. * @throws IllegalArgumentException if region contains fewer than 2 cells
  307. */
  308. @Override
  309. public int addMergedRegionUnsafe(CellRangeAddress region) {
  310. return addMergedRegion(region, false);
  311. }
  312. /**
  313. * Adds a merged region of cells (hence those cells form one).
  314. * If validate is true, check to make sure adding the merged region to the sheet doesn't create a corrupt workbook
  315. * If validate is false, skips the expensive merged region checks, but may produce a corrupt workbook.
  316. *
  317. * @param region to merge
  318. * @param validate whether to validate merged region
  319. * @return 0-based index of this region
  320. * @throws IllegalArgumentException if region contains fewer than 2 cells (this check is inexpensive and is performed regardless of <tt>validate</tt>)
  321. * @throws IllegalStateException if region intersects with a multi-cell array formula
  322. * @throws IllegalStateException if region intersects with an existing region on this sheet
  323. */
  324. private int addMergedRegion(CellRangeAddress region, boolean validate) {
  325. if (region.getNumberOfCells() < 2) {
  326. throw new IllegalArgumentException("Merged region " + region.formatAsString() + " must contain 2 or more cells");
  327. }
  328. region.validate(SpreadsheetVersion.EXCEL2007);
  329. if (validate) {
  330. // throw IllegalStateException if the argument CellRangeAddress intersects with
  331. // a multi-cell array formula defined in this sheet
  332. validateArrayFormulas(region);
  333. // Throw IllegalStateException if the argument CellRangeAddress intersects with
  334. // a merged region already in this sheet
  335. validateMergedRegions(region);
  336. }
  337. CTMergeCells ctMergeCells = worksheet.isSetMergeCells() ? worksheet.getMergeCells() : worksheet.addNewMergeCells();
  338. CTMergeCell ctMergeCell = ctMergeCells.addNewMergeCell();
  339. ctMergeCell.setRef(region.formatAsString());
  340. long count = ctMergeCells.getCount();
  341. if (count == 0) {
  342. count=ctMergeCells.sizeOfMergeCellArray();
  343. } else {
  344. count++;
  345. }
  346. // also adjust the number of merged regions overall
  347. ctMergeCells.setCount(count);
  348. return Math.toIntExact(count-1);
  349. }
  350. /**
  351. * Verify that the candidate region does not intersect with an existing multi-cell array formula in this sheet
  352. *
  353. * @param region a region that is validated.
  354. * @throws IllegalStateException if candidate region intersects an existing array formula in this sheet
  355. */
  356. private void validateArrayFormulas(CellRangeAddress region) {
  357. // FIXME: this may be faster if it looped over array formulas directly rather than looping over each cell in
  358. // the region and searching if that cell belongs to an array formula
  359. int firstRow = region.getFirstRow();
  360. int firstColumn = region.getFirstColumn();
  361. int lastRow = region.getLastRow();
  362. int lastColumn = region.getLastColumn();
  363. // for each cell in sheet, if cell belongs to an array formula, check if merged region intersects array formula cells
  364. for (int rowIn = firstRow; rowIn <= lastRow; rowIn++) {
  365. XSSFRow row = getRow(rowIn);
  366. if (row == null) {
  367. continue;
  368. }
  369. for (int colIn = firstColumn; colIn <= lastColumn; colIn++) {
  370. XSSFCell cell = row.getCell(colIn);
  371. if (cell == null) {
  372. continue;
  373. }
  374. if (cell.isPartOfArrayFormulaGroup()) {
  375. CellRangeAddress arrayRange = cell.getArrayFormulaRange();
  376. if (arrayRange.getNumberOfCells() > 1 && region.intersects(arrayRange)) {
  377. String msg = "The range " + region.formatAsString() + " intersects with a multi-cell array formula. " +
  378. "You cannot merge cells of an array.";
  379. throw new IllegalStateException(msg);
  380. }
  381. }
  382. }
  383. }
  384. }
  385. /**
  386. * Verify that none of the merged regions intersect a multi-cell array formula in this sheet
  387. *
  388. * @throws IllegalStateException if candidate region intersects an existing array formula in this sheet
  389. */
  390. private void checkForMergedRegionsIntersectingArrayFormulas() {
  391. for (CellRangeAddress region : getMergedRegions()) {
  392. validateArrayFormulas(region);
  393. }
  394. }
  395. /**
  396. * Verify that candidate region does not intersect with an existing merged region in this sheet
  397. *
  398. * @param candidateRegion the range of cells to verify
  399. * @throws IllegalStateException if candidate region intersects an existing merged region in this sheet (or candidateRegion is already merged in this sheet)
  400. */
  401. private void validateMergedRegions(CellRangeAddress candidateRegion) {
  402. for (final CellRangeAddress existingRegion : getMergedRegions()) {
  403. if (existingRegion.intersects(candidateRegion)) {
  404. throw new IllegalStateException("Cannot add merged region " + candidateRegion.formatAsString() +
  405. " to sheet because it overlaps with an existing merged region (" + existingRegion.formatAsString() + ").");
  406. }
  407. }
  408. }
  409. /**
  410. * Verify that no merged regions intersect another merged region in this sheet.
  411. *
  412. * @throws IllegalStateException if at least one region intersects with another merged region in this sheet
  413. */
  414. private void checkForIntersectingMergedRegions() {
  415. final List<CellRangeAddress> regions = getMergedRegions();
  416. final int size = regions.size();
  417. for (int i=0; i < size; i++) {
  418. final CellRangeAddress region = regions.get(i);
  419. for (final CellRangeAddress other : regions.subList(i+1, regions.size())) {
  420. if (region.intersects(other)) {
  421. String msg = "The range " + region.formatAsString() +
  422. " intersects with another merged region " +
  423. other.formatAsString() + " in this sheet";
  424. throw new IllegalStateException(msg);
  425. }
  426. }
  427. }
  428. }
  429. /**
  430. * Verify that merged regions do not intersect multi-cell array formulas and
  431. * no merged regions intersect another merged region in this sheet.
  432. *
  433. * @throws IllegalStateException if region intersects with a multi-cell array formula
  434. * @throws IllegalStateException if at least one region intersects with another merged region in this sheet
  435. */
  436. @Override
  437. public void validateMergedRegions() {
  438. checkForMergedRegionsIntersectingArrayFormulas();
  439. checkForIntersectingMergedRegions();
  440. }
  441. /**
  442. * Adjusts the column width to fit the contents.
  443. *
  444. * This process can be relatively slow on large sheets, so this should
  445. * normally only be called once per column, at the end of your
  446. * processing.
  447. *
  448. * @param column the column index
  449. */
  450. @Override
  451. public void autoSizeColumn(int column) {
  452. autoSizeColumn(column, false);
  453. }
  454. /**
  455. * Adjusts the column width to fit the contents.
  456. * <p>
  457. * This process can be relatively slow on large sheets, so this should
  458. * normally only be called once per column, at the end of your
  459. * processing.
  460. * </p>
  461. * You can specify whether the content of merged cells should be considered or ignored.
  462. * Default is to ignore merged cells.
  463. *
  464. * @param column the column index
  465. * @param useMergedCells whether to use the contents of merged cells when calculating the width of the column
  466. */
  467. @Override
  468. public void autoSizeColumn(int column, boolean useMergedCells) {
  469. double width = SheetUtil.getColumnWidth(this, column, useMergedCells);
  470. if (width != -1) {
  471. width *= 256;
  472. int maxColumnWidth = 255*256; // The maximum column width for an individual cell is 255 characters
  473. if (width > maxColumnWidth) {
  474. width = maxColumnWidth;
  475. }
  476. setColumnWidth(column, Math.toIntExact(Math.round(width)));
  477. columnHelper.setColBestFit(column, true);
  478. }
  479. }
  480. /**
  481. * Return the sheet's existing drawing, or null if there isn't yet one.
  482. *
  483. * Use {@link #createDrawingPatriarch()} to get or create
  484. *
  485. * @return a SpreadsheetML drawing
  486. */
  487. @Override
  488. public XSSFDrawing getDrawingPatriarch() {
  489. CTDrawing ctDrawing = getCTDrawing();
  490. if (ctDrawing != null) {
  491. // Search the referenced drawing in the list of the sheet's relations
  492. for (RelationPart rp : getRelationParts()){
  493. POIXMLDocumentPart p = rp.getDocumentPart();
  494. if (p instanceof XSSFDrawing) {
  495. XSSFDrawing dr = (XSSFDrawing)p;
  496. String drId = rp.getRelationship().getId();
  497. if (drId.equals(ctDrawing.getId())){
  498. return dr;
  499. }
  500. break;
  501. }
  502. }
  503. logger.log(POILogger.ERROR, "Can't find drawing with id=", ctDrawing.getId(), " in the list of the sheet's relationships");
  504. }
  505. return null;
  506. }
  507. /**
  508. * Create a new SpreadsheetML drawing. If this sheet already contains a drawing - return that.
  509. *
  510. * @return a SpreadsheetML drawing
  511. */
  512. @Override
  513. public XSSFDrawing createDrawingPatriarch() {
  514. CTDrawing ctDrawing = getCTDrawing();
  515. if (ctDrawing != null) {
  516. return getDrawingPatriarch();
  517. }
  518. // Default drawingNumber = #drawings.size() + 1
  519. int drawingNumber = getPackagePart().getPackage().getPartsByContentType(XSSFRelation.DRAWINGS.getContentType()).size() + 1;
  520. drawingNumber = getNextPartNumber(XSSFRelation.DRAWINGS, drawingNumber);
  521. RelationPart rp = createRelationship(XSSFRelation.DRAWINGS, XSSFFactory.getInstance(), drawingNumber, false);
  522. XSSFDrawing drawing = rp.getDocumentPart();
  523. String relId = rp.getRelationship().getId();
  524. //add CT_Drawing element which indicates that this sheet contains drawing components built on the drawingML platform.
  525. //The relationship Id references the part containing the drawingML definitions.
  526. ctDrawing = worksheet.addNewDrawing();
  527. ctDrawing.setId(relId);
  528. // Return the newly created drawing
  529. return drawing;
  530. }
  531. /**
  532. * Get VML drawing for this sheet (aka 'legacy' drawig)
  533. *
  534. * @param autoCreate if true, then a new VML drawing part is created
  535. *
  536. * @return the VML drawing of <code>null</code> if the drawing was not found and autoCreate=false
  537. */
  538. protected XSSFVMLDrawing getVMLDrawing(boolean autoCreate) {
  539. XSSFVMLDrawing drawing = null;
  540. CTLegacyDrawing ctDrawing = getCTLegacyDrawing();
  541. if(ctDrawing == null) {
  542. if(autoCreate) {
  543. //drawingNumber = #drawings.size() + 1
  544. int drawingNumber = getPackagePart().getPackage().getPartsByContentType(XSSFRelation.VML_DRAWINGS.getContentType()).size() + 1;
  545. RelationPart rp = createRelationship(XSSFRelation.VML_DRAWINGS, XSSFFactory.getInstance(), drawingNumber, false);
  546. drawing = rp.getDocumentPart();
  547. String relId = rp.getRelationship().getId();
  548. //add CTLegacyDrawing element which indicates that this sheet contains drawing components built on the drawingML platform.
  549. //The relationship Id references the part containing the drawing definitions.
  550. ctDrawing = worksheet.addNewLegacyDrawing();
  551. ctDrawing.setId(relId);
  552. }
  553. } else {
  554. //search the referenced drawing in the list of the sheet's relations
  555. final String id = ctDrawing.getId();
  556. for (RelationPart rp : getRelationParts()){
  557. POIXMLDocumentPart p = rp.getDocumentPart();
  558. if(p instanceof XSSFVMLDrawing) {
  559. XSSFVMLDrawing dr = (XSSFVMLDrawing)p;
  560. String drId = rp.getRelationship().getId();
  561. if (drId.equals(id)) {
  562. drawing = dr;
  563. break;
  564. }
  565. // do not break here since drawing has not been found yet (see bug 52425)
  566. }
  567. }
  568. if(drawing == null){
  569. logger.log(POILogger.ERROR, "Can't find VML drawing with id=", id, " in the list of the sheet's relationships");
  570. }
  571. }
  572. return drawing;
  573. }
  574. protected CTDrawing getCTDrawing() {
  575. return worksheet.getDrawing();
  576. }
  577. protected CTLegacyDrawing getCTLegacyDrawing() {
  578. return worksheet.getLegacyDrawing();
  579. }
  580. /**
  581. * Creates a split (freezepane). Any existing freezepane or split pane is overwritten.
  582. * @param colSplit Horizontal position of split.
  583. * @param rowSplit Vertical position of split.
  584. */
  585. @Override
  586. public void createFreezePane(int colSplit, int rowSplit) {
  587. createFreezePane( colSplit, rowSplit, colSplit, rowSplit );
  588. }
  589. /**
  590. * Creates a split (freezepane). Any existing freezepane or split pane is overwritten.
  591. *
  592. * <p>
  593. * If both colSplit and rowSplit are zero then the existing freeze pane is removed
  594. * </p>
  595. *
  596. * @param colSplit Horizontal position of split.
  597. * @param rowSplit Vertical position of split.
  598. * @param leftmostColumn Left column visible in right pane.
  599. * @param topRow Top row visible in bottom pane
  600. */
  601. @Override
  602. public void createFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow) {
  603. final boolean removeSplit = colSplit == 0 && rowSplit == 0;
  604. final CTSheetView ctView = getDefaultSheetView(!removeSplit);
  605. if (ctView != null) {
  606. ctView.setSelectionArray(null);
  607. }
  608. // If both colSplit and rowSplit are zero then the existing freeze pane is removed
  609. if (removeSplit) {
  610. if (ctView != null && ctView.isSetPane()) {
  611. ctView.unsetPane();
  612. }
  613. return;
  614. }
  615. assert(ctView != null);
  616. final CTPane pane = (ctView.isSetPane()) ? ctView.getPane() : ctView.addNewPane();
  617. assert(pane != null);
  618. if (colSplit > 0) {
  619. pane.setXSplit(colSplit);
  620. } else if (pane.isSetXSplit()) {
  621. pane.unsetXSplit();
  622. }
  623. if (rowSplit > 0) {
  624. pane.setYSplit(rowSplit);
  625. } else if(pane.isSetYSplit()) {
  626. pane.unsetYSplit();
  627. }
  628. STPane.Enum activePane = STPane.BOTTOM_RIGHT;
  629. int pRow = topRow, pCol = leftmostColumn;
  630. if (rowSplit == 0) {
  631. pRow = 0;
  632. activePane = STPane.TOP_RIGHT;
  633. } else if (colSplit == 0) {
  634. pCol = 0;
  635. activePane = STPane.BOTTOM_LEFT;
  636. }
  637. pane.setState(STPaneState.FROZEN);
  638. pane.setTopLeftCell(new CellReference(pRow, pCol).formatAsString());
  639. pane.setActivePane(activePane);
  640. ctView.addNewSelection().setPane(activePane);
  641. }
  642. /**
  643. * Create a new row within the sheet and return the high level representation
  644. *
  645. * Note: If a row already exists at this position, it is removed/overwritten and
  646. * any existing cell is removed!
  647. *
  648. * @param rownum row number
  649. * @return High level {@link XSSFRow} object representing a row in the sheet
  650. * @see #removeRow(org.apache.poi.ss.usermodel.Row)
  651. */
  652. @Override
  653. public XSSFRow createRow(int rownum) {
  654. // Performance optimization: explicit boxing is slightly faster than auto-unboxing, though may use more memory
  655. //noinspection UnnecessaryBoxing
  656. final Integer rownumI = Integer.valueOf(rownum); // NOSONAR
  657. CTRow ctRow;
  658. XSSFRow prev = _rows.get(rownumI);
  659. if(prev != null){
  660. // the Cells in an existing row are invalidated on-purpose, in order to clean up correctly, we
  661. // need to call the remove, so things like ArrayFormulas and CalculationChain updates are done
  662. // correctly.
  663. // We remove the cell this way as the internal cell-list is changed by the remove call and
  664. // thus would cause ConcurrentModificationException otherwise
  665. while(prev.getFirstCellNum() != -1) {
  666. prev.removeCell(prev.getCell(prev.getFirstCellNum()));
  667. }
  668. ctRow = prev.getCTRow();
  669. ctRow.set(CTRow.Factory.newInstance());
  670. } else {
  671. if(_rows.isEmpty() || rownum > _rows.lastKey()) {
  672. // we can append the new row at the end
  673. ctRow = worksheet.getSheetData().addNewRow();
  674. } else {
  675. // get number of rows where row index < rownum
  676. // --> this tells us where our row should go
  677. int idx = _rows.headMap(rownumI).size();
  678. ctRow = worksheet.getSheetData().insertNewRow(idx);
  679. }
  680. }
  681. XSSFRow r = new XSSFRow(ctRow, this);
  682. r.setRowNum(rownum);
  683. _rows.put(rownumI, r);
  684. return r;
  685. }
  686. /**
  687. * Creates a split pane. Any existing freezepane or split pane is overwritten.
  688. * @param xSplitPos Horizontal position of split (in 1/20th of a point).
  689. * @param ySplitPos Vertical position of split (in 1/20th of a point).
  690. * @param topRow Top row visible in bottom pane
  691. * @param leftmostColumn Left column visible in right pane.
  692. * @param activePane Active pane. One of: PANE_LOWER_RIGHT,
  693. * PANE_UPPER_RIGHT, PANE_LOWER_LEFT, PANE_UPPER_LEFT
  694. * @see org.apache.poi.ss.usermodel.Sheet#PANE_LOWER_LEFT
  695. * @see org.apache.poi.ss.usermodel.Sheet#PANE_LOWER_RIGHT
  696. * @see org.apache.poi.ss.usermodel.Sheet#PANE_UPPER_LEFT
  697. * @see org.apache.poi.ss.usermodel.Sheet#PANE_UPPER_RIGHT
  698. */
  699. @Override
  700. public void createSplitPane(int xSplitPos, int ySplitPos, int leftmostColumn, int topRow, int activePane) {
  701. createFreezePane(xSplitPos, ySplitPos, leftmostColumn, topRow);
  702. if (xSplitPos > 0 || ySplitPos > 0) {
  703. final CTPane pane = getPane(true);
  704. pane.setState(STPaneState.SPLIT);
  705. pane.setActivePane(STPane.Enum.forInt(activePane));
  706. }
  707. }
  708. /**
  709. * Return cell comment at row, column, if one exists. Otherwise returns null.
  710. *
  711. * @param address the location of the cell comment
  712. * @return the cell comment, if one exists. Otherwise return null.
  713. */
  714. @Override
  715. public XSSFComment getCellComment(CellAddress address) {
  716. if (sheetComments == null) {
  717. return null;
  718. }
  719. final int row = address.getRow();
  720. final int column = address.getColumn();
  721. CellAddress ref = new CellAddress(row, column);
  722. CTComment ctComment = sheetComments.getCTComment(ref);
  723. if(ctComment == null) {
  724. return null;
  725. }
  726. XSSFVMLDrawing vml = getVMLDrawing(false);
  727. return new XSSFComment(sheetComments, ctComment,
  728. vml == null ? null : vml.findCommentShape(row, column));
  729. }
  730. /**
  731. * Returns all cell comments on this sheet.
  732. * @return A map of each Comment in the sheet, keyed on the cell address where
  733. * the comment is located.
  734. */
  735. @Override
  736. public Map<CellAddress, XSSFComment> getCellComments() {
  737. if (sheetComments == null) {
  738. return Collections.emptyMap();
  739. }
  740. // the cell comments in sheetComments.getCellComments() do not have the client anchors set
  741. Map<CellAddress, XSSFComment> map = new HashMap<>();
  742. for(Iterator<CellAddress> iter = sheetComments.getCellAddresses(); iter.hasNext(); ) {
  743. CellAddress address = iter.next();
  744. map.put(address, getCellComment(address));
  745. }
  746. return map;
  747. }
  748. /**
  749. * Get a Hyperlink in this sheet anchored at row, column
  750. *
  751. * @param row The row where the hyperlink is anchored
  752. * @param column The column where the hyperlinkn is anchored
  753. * @return hyperlink if there is a hyperlink anchored at row, column; otherwise returns null
  754. */
  755. @Override
  756. public XSSFHyperlink getHyperlink(int row, int column) {
  757. return getHyperlink(new CellAddress(row, column));
  758. }
  759. /**
  760. * Get a Hyperlink in this sheet located in a cell specified by {code addr}
  761. *
  762. * @param addr The address of the cell containing the hyperlink
  763. * @return hyperlink if there is a hyperlink anchored at {@code addr}; otherwise returns {@code null}
  764. * @since POI 3.15 beta 3
  765. */
  766. @Override
  767. public XSSFHyperlink getHyperlink(CellAddress addr) {
  768. String ref = addr.formatAsString();
  769. for(XSSFHyperlink hyperlink : hyperlinks) {
  770. if(hyperlink.getCellRef().equals(ref)) {
  771. return hyperlink;
  772. }
  773. }
  774. return null;
  775. }
  776. /**
  777. * Get a list of Hyperlinks in this sheet
  778. *
  779. * @return Hyperlinks for the sheet
  780. */
  781. @Override
  782. public List<XSSFHyperlink> getHyperlinkList() {
  783. return Collections.unmodifiableList(hyperlinks);
  784. }
  785. private int[] getBreaks(CTPageBreak ctPageBreak) {
  786. CTBreak[] brkArray = ctPageBreak.getBrkArray();
  787. int[] breaks = new int[brkArray.length];
  788. for (int i = 0 ; i < brkArray.length ; i++) {
  789. breaks[i] = Math.toIntExact(brkArray[i].getId() - 1);
  790. }
  791. return breaks;
  792. }
  793. private void removeBreak(int index, CTPageBreak ctPageBreak) {
  794. int index1 = index + 1;
  795. CTBreak[] brkArray = ctPageBreak.getBrkArray();
  796. for (int i = 0 ; i < brkArray.length ; i++) {
  797. if (brkArray[i].getId() == index1) {
  798. ctPageBreak.removeBrk(i);
  799. // TODO: check if we can break here, i.e. if a page can have more than 1 break on the same id
  800. }
  801. }
  802. }
  803. /**
  804. * Vertical page break information used for print layout view, page layout view, drawing print breaks
  805. * in normal view, and for printing the worksheet.
  806. *
  807. * @return column indexes of all the vertical page breaks, never <code>null</code>
  808. */
  809. @Override
  810. public int[] getColumnBreaks() {
  811. return worksheet.isSetColBreaks() ? getBreaks(worksheet.getColBreaks()) : new int[0];
  812. }
  813. /**
  814. * Get the actual column width (in units of 1/256th of a character width )
  815. *
  816. * <p>
  817. * Note, the returned value is always gerater that {@link #getDefaultColumnWidth()} because the latter does not include margins.
  818. * Actual column width measured as the number of characters of the maximum digit width of the
  819. * numbers 0, 1, 2, ..., 9 as rendered in the normal style's font. There are 4 pixels of margin
  820. * padding (two on each side), plus 1 pixel padding for the gridlines.
  821. * </p>
  822. *
  823. * @param columnIndex - the column to set (0-based)
  824. * @return width - the width in units of 1/256th of a character width
  825. */
  826. @Override
  827. public int getColumnWidth(int columnIndex) {
  828. CTCol col = columnHelper.getColumn(columnIndex, false);
  829. double width = col == null || !col.isSetWidth() ? getDefaultColumnWidth() : col.getWidth();
  830. return Math.toIntExact(Math.round(width*256));
  831. }
  832. /**
  833. * Get the actual column width in pixels
  834. *
  835. * <p>
  836. * Please note, that this method works correctly only for workbooks
  837. * with the default font size (Calibri 11pt for .xlsx).
  838. * </p>
  839. */
  840. @Override
  841. public float getColumnWidthInPixels(int columnIndex) {
  842. float widthIn256 = getColumnWidth(columnIndex);
  843. return (float)(widthIn256/256.0*Units.DEFAULT_CHARACTER_WIDTH);
  844. }
  845. /**
  846. * Get the default column width for the sheet (if the columns do not define their own width) in
  847. * characters.
  848. * <p>
  849. * Note, this value is different from {@link #getColumnWidth(int)}. The latter is always greater and includes
  850. * 4 pixels of margin padding (two on each side), plus 1 pixel padding for the gridlines.
  851. * </p>
  852. * @return column width, default value is 8
  853. */
  854. @Override
  855. public int getDefaultColumnWidth() {
  856. CTSheetFormatPr pr = worksheet.getSheetFormatPr();
  857. return pr == null ? 8 : Math.toIntExact(pr.getBaseColWidth());
  858. }
  859. /**
  860. * Get the default row height for the sheet (if the rows do not define their own height) in
  861. * twips (1/20 of a point)
  862. *
  863. * @return default row height
  864. */
  865. @Override
  866. public short getDefaultRowHeight() {
  867. return (short)(getDefaultRowHeightInPoints() * Font.TWIPS_PER_POINT);
  868. }
  869. /**
  870. * Get the default row height for the sheet measued in point size (if the rows do not define their own height).
  871. *
  872. * @return default row height in points
  873. */
  874. @Override
  875. public float getDefaultRowHeightInPoints() {
  876. CTSheetFormatPr pr = worksheet.getSheetFormatPr();
  877. return (float)(pr == null ? 0 : pr.getDefaultRowHeight());
  878. }
  879. private CTSheetFormatPr getSheetTypeSheetFormatPr() {
  880. return worksheet.isSetSheetFormatPr() ?
  881. worksheet.getSheetFormatPr() :
  882. worksheet.addNewSheetFormatPr();
  883. }
  884. /**
  885. * Returns the CellStyle that applies to the given
  886. * (0 based) column, or null if no style has been
  887. * set for that column
  888. */
  889. @Override
  890. public CellStyle getColumnStyle(int column) {
  891. int idx = columnHelper.getColDefaultStyle(column);
  892. return getWorkbook().getCellStyleAt((short)(idx == -1 ? 0 : idx));
  893. }
  894. /**
  895. * Sets whether the worksheet is displayed from right to left instead of from left to right.
  896. *
  897. * @param value true for right to left, false otherwise.
  898. */
  899. @Override
  900. public void setRightToLeft(boolean value) {
  901. final CTSheetView dsv = getDefaultSheetView(true);
  902. assert(dsv != null);
  903. dsv.setRightToLeft(value);
  904. }
  905. /**
  906. * Whether the text is displayed in right-to-left mode in the window
  907. *
  908. * @return whether the text is displayed in right-to-left mode in the window
  909. */
  910. @Override
  911. public boolean isRightToLeft() {
  912. final CTSheetView dsv = getDefaultSheetView(false);
  913. return (dsv != null && dsv.getRightToLeft());
  914. }
  915. /**
  916. * Get whether to display the guts or not,
  917. * default value is true
  918. *
  919. * @return boolean - guts or no guts
  920. */
  921. @Override
  922. public boolean getDisplayGuts() {
  923. CTSheetPr sheetPr = getSheetTypeSheetPr();
  924. CTOutlinePr outlinePr = sheetPr.getOutlinePr() == null ? CTOutlinePr.Factory.newInstance() : sheetPr.getOutlinePr();
  925. return outlinePr.getShowOutlineSymbols();
  926. }
  927. /**
  928. * Set whether to display the guts or not
  929. *
  930. * @param value - guts or no guts
  931. */
  932. @Override
  933. public void setDisplayGuts(boolean value) {
  934. CTSheetPr sheetPr = getSheetTypeSheetPr();
  935. CTOutlinePr outlinePr = sheetPr.getOutlinePr() == null ? sheetPr.addNewOutlinePr() : sheetPr.getOutlinePr();
  936. outlinePr.setShowOutlineSymbols(value);
  937. }
  938. /**
  939. * Gets the flag indicating whether the window should show 0 (zero) in cells containing zero value.
  940. * When false, cells with zero value appear blank instead of showing the number zero.
  941. *
  942. * @return whether all zero values on the worksheet are displayed (defaults to true)
  943. */
  944. @Override
  945. public boolean isDisplayZeros(){
  946. final CTSheetView dsv = getDefaultSheetView(false);
  947. return (dsv == null) || dsv.getShowZeros();
  948. }
  949. /**
  950. * Set whether the window should show 0 (zero) in cells containing zero value.
  951. * When false, cells with zero value appear blank instead of showing the number zero.
  952. *
  953. * @param value whether to display or hide all zero values on the worksheet
  954. */
  955. @Override
  956. public void setDisplayZeros(boolean value){
  957. final CTSheetView view = getDefaultSheetView(true);
  958. assert(view != null);
  959. view.setShowZeros(value);
  960. }
  961. /**
  962. * Gets the first row on the sheet
  963. *
  964. * @return the number of the first logical row on the sheet, zero based
  965. */
  966. @Override
  967. public int getFirstRowNum() {
  968. return _rows.isEmpty() ? -1 : _rows.firstKey();
  969. }
  970. /**
  971. * Flag indicating whether the Fit to Page print option is enabled.
  972. *
  973. * @return <code>true</code>
  974. */
  975. @Override
  976. public boolean getFitToPage() {
  977. CTSheetPr sheetPr = getSheetTypeSheetPr();
  978. CTPageSetUpPr psSetup = (sheetPr == null || !sheetPr.isSetPageSetUpPr()) ?
  979. CTPageSetUpPr.Factory.newInstance() : sheetPr.getPageSetUpPr();
  980. return psSetup.getFitToPage();
  981. }
  982. private CTSheetPr getSheetTypeSheetPr() {
  983. if (worksheet.getSheetPr() == null) {
  984. worksheet.setSheetPr(CTSheetPr.Factory.newInstance());
  985. }
  986. return worksheet.getSheetPr();
  987. }
  988. private CTHeaderFooter getSheetTypeHeaderFooter() {
  989. if (worksheet.getHeaderFooter() == null) {
  990. worksheet.setHeaderFooter(CTHeaderFooter.Factory.newInstance());
  991. }
  992. return worksheet.getHeaderFooter();
  993. }
  994. /**
  995. * Returns the default footer for the sheet,
  996. * creating one as needed.
  997. * You may also want to look at
  998. * {@link #getFirstFooter()},
  999. * {@link #getOddFooter()} and
  1000. * {@link #getEvenFooter()}
  1001. */
  1002. @Override
  1003. public Footer getFooter() {
  1004. // The default footer is an odd footer
  1005. return getOddFooter();
  1006. }
  1007. /**
  1008. * Returns the default header for the sheet,
  1009. * creating one as needed.
  1010. * You may also want to look at
  1011. * {@link #getFirstHeader()},
  1012. * {@link #getOddHeader()} and
  1013. * {@link #getEvenHeader()}
  1014. */
  1015. @Override
  1016. public Header getHeader() {
  1017. // The default header is an odd header
  1018. return getOddHeader();
  1019. }
  1020. /**
  1021. * Returns the odd footer. Used on all pages unless
  1022. * other footers also present, when used on only
  1023. * odd pages.
  1024. */
  1025. public Footer getOddFooter() {
  1026. return new XSSFOddFooter(getSheetTypeHeaderFooter());
  1027. }
  1028. /**
  1029. * Returns the even footer. Not there by default, but
  1030. * when set, used on even pages.
  1031. */
  1032. public Footer getEvenFooter() {
  1033. return new XSSFEvenFooter(getSheetTypeHeaderFooter());
  1034. }
  1035. /**
  1036. * Returns the first page footer. Not there by
  1037. * default, but when set, used on the first page.
  1038. */
  1039. public Footer getFirstFooter() {
  1040. return new XSSFFirstFooter(getSheetTypeHeaderFooter());
  1041. }
  1042. /**
  1043. * Returns the odd header. Used on all pages unless
  1044. * other headers also present, when used on only
  1045. * odd pages.
  1046. */
  1047. public Header getOddHeader() {
  1048. return new XSSFOddHeader(getSheetTypeHeaderFooter());
  1049. }
  1050. /**
  1051. * Returns the even header. Not there by default, but
  1052. * when set, used on even pages.
  1053. */
  1054. public Header getEvenHeader() {
  1055. return new XSSFEvenHeader(getSheetTypeHeaderFooter());
  1056. }
  1057. /**
  1058. * Returns the first page header. Not there by
  1059. * default, but when set, used on the first page.
  1060. */
  1061. public Header getFirstHeader() {
  1062. return new XSSFFirstHeader(getSheetTypeHeaderFooter());
  1063. }
  1064. /**
  1065. * Determine whether printed output for this sheet will be horizontally centered.
  1066. */
  1067. @Override
  1068. public boolean getHorizontallyCenter() {
  1069. CTPrintOptions opts = worksheet.getPrintOptions();
  1070. return opts != null && opts.getHorizontalCentered();
  1071. }
  1072. @Override
  1073. public int getLastRowNum() {
  1074. // _rows.getLastKey() (O(logN)) or caching last row (O(1))?
  1075. // A test with 1_000_000 rows shows that querying getLastRowNum with lastKey() implementation takes ~40 ms,
  1076. // and ~1.2 ms with cached implementation. 40 ms is negligible compared to the time of evaluation a million
  1077. // cells, and the lastKey implementation is much more elegant and less error prone than caching.
  1078. return _rows.isEmpty() ? -1 : _rows.lastKey();
  1079. }
  1080. @Override
  1081. public short getLeftCol() {
  1082. String cellRef = worksheet.getSheetViews().getSheetViewArray(0).getTopLeftCell();
  1083. if(cellRef == null) {
  1084. return 0;
  1085. }
  1086. CellReference cellReference = new CellReference(cellRef);
  1087. return cellReference.getCol();
  1088. }
  1089. /**
  1090. * Gets the size of the margin in inches.
  1091. *
  1092. * @param margin which margin to get
  1093. * @return the size of the margin
  1094. * @see Sheet#LeftMargin
  1095. * @see Sheet#RightMargin
  1096. * @see Sheet#TopMargin
  1097. * @see Sheet#BottomMargin
  1098. * @see Sheet#HeaderMargin
  1099. * @see Sheet#FooterMargin
  1100. */
  1101. @Override
  1102. public double getMargin(short margin) {
  1103. if (!worksheet.isSetPageMargins()) {
  1104. return 0;
  1105. }
  1106. CTPageMargins pageMargins = worksheet.getPageMargins();
  1107. switch (margin) {
  1108. case LeftMargin:
  1109. return pageMargins.getLeft();
  1110. case RightMargin:
  1111. return pageMargins.getRight();
  1112. case TopMargin:
  1113. return pageMargins.getTop();
  1114. case BottomMargin:
  1115. return pageMargins.getBottom();
  1116. case HeaderMargin:
  1117. return pageMargins.getHeader();
  1118. case FooterMargin:
  1119. return pageMargins.getFooter();
  1120. default :
  1121. throw new IllegalArgumentException("Unknown margin constant: " + margin);
  1122. }
  1123. }
  1124. /**
  1125. * Sets the size of the margin in inches.
  1126. *
  1127. * @param margin which margin to get
  1128. * @param size the size of the margin
  1129. * @see Sheet#LeftMargin
  1130. * @see Sheet#RightMargin
  1131. * @see Sheet#TopMargin
  1132. * @see Sheet#BottomMargin
  1133. * @see Sheet#HeaderMargin
  1134. * @see Sheet#FooterMargin
  1135. */
  1136. @Override
  1137. public void setMargin(short margin, double size) {
  1138. CTPageMargins pageMargins = worksheet.isSetPageMargins() ?
  1139. worksheet.getPageMargins() : worksheet.addNewPageMargins();
  1140. switch (margin) {
  1141. case LeftMargin:
  1142. pageMargins.setLeft(size);
  1143. break;
  1144. case RightMargin:
  1145. pageMargins.setRight(size);
  1146. break;
  1147. case TopMargin:
  1148. pageMargins.setTop(size);
  1149. break;
  1150. case BottomMargin:
  1151. pageMargins.setBottom(size);
  1152. break;
  1153. case HeaderMargin:
  1154. pageMargins.setHeader(size);
  1155. break;
  1156. case FooterMargin:
  1157. pageMargins.setFooter(size);
  1158. break;
  1159. default :
  1160. throw new IllegalArgumentException( "Unknown margin constant: " + margin );
  1161. }
  1162. }
  1163. /**
  1164. * Returns the merged region at the specified index. If you want multiple
  1165. * regions, it is faster to call {@link #getMergedRegions()} than to call
  1166. * this each time.
  1167. *
  1168. * @return the merged region at the specified index
  1169. */
  1170. @Override
  1171. public CellRangeAddress getMergedRegion(int index) {
  1172. CTMergeCells ctMergeCells = worksheet.getMergeCells();
  1173. if(ctMergeCells == null) {
  1174. throw new IllegalStateException("This worksheet does not contain merged regions");
  1175. }
  1176. CTMergeCell ctMergeCell = ctMergeCells.getMergeCellArray(index);
  1177. String ref = ctMergeCell.getRef();
  1178. return CellRangeAddress.valueOf(ref);
  1179. }
  1180. /**
  1181. * Returns the list of merged regions. If you want multiple regions, this is
  1182. * faster than calling {@link #getMergedRegion(int)} each time.
  1183. *
  1184. * @return the list of merged regions
  1185. */
  1186. @Override
  1187. public List<CellRangeAddress> getMergedRegions() {
  1188. List<CellRangeAddress> addresses = new ArrayList<>();
  1189. CTMergeCells ctMergeCells = worksheet.getMergeCells();
  1190. if(ctMergeCells == null) {
  1191. return addresses;
  1192. }
  1193. for(CTMergeCell ctMergeCell : ctMergeCells.getMergeCellArray()) {
  1194. String ref = ctMergeCell.getRef();
  1195. addresses.add(CellRangeAddress.valueOf(ref));
  1196. }
  1197. return addresses;
  1198. }
  1199. /**
  1200. * Returns the number of merged regions defined in this worksheet
  1201. *
  1202. * @return number of merged regions in this worksheet
  1203. */
  1204. @Override
  1205. public int getNumMergedRegions() {
  1206. CTMergeCells ctMergeCells = worksheet.getMergeCells();
  1207. return ctMergeCells == null ? 0 : ctMergeCells.sizeOfMergeCellArray();
  1208. }
  1209. public int getNumHyperlinks() {
  1210. return hyperlinks.size();
  1211. }
  1212. /**
  1213. * Returns the information regarding the currently configured pane (split or freeze).
  1214. *
  1215. * @return null if no pane configured, or the pane information.
  1216. */
  1217. @Override
  1218. public PaneInformation getPaneInformation() {
  1219. final CTPane pane = getPane(false);
  1220. // no pane configured
  1221. if(pane == null) {
  1222. return null;
  1223. }
  1224. short row = 0, col = 0;
  1225. if (pane.isSetTopLeftCell()) {
  1226. final CellReference cellRef = new CellReference(pane.getTopLeftCell());
  1227. row = (short)cellRef.getRow();
  1228. col = cellRef.getCol();
  1229. }
  1230. final short x = (short)pane.getXSplit();
  1231. final short y = (short)pane.getYSplit();
  1232. final byte active = (byte)(pane.getActivePane().intValue() - 1);
  1233. final boolean frozen = pane.getState() == STPaneState.FROZEN;
  1234. return new PaneInformation(x, y, row, col, active, frozen);
  1235. }
  1236. /**
  1237. * Returns the number of physically defined rows (NOT the number of rows in the sheet)
  1238. *
  1239. * @return the number of physically defined rows
  1240. */
  1241. @Override
  1242. public int getPhysicalNumberOfRows() {
  1243. return _rows.size();
  1244. }
  1245. /**
  1246. * Gets the print setup object.
  1247. *
  1248. * @return The user model for the print setup object.
  1249. */
  1250. @Override
  1251. public XSSFPrintSetup getPrintSetup() {
  1252. return new XSSFPrintSetup(worksheet);
  1253. }
  1254. /**
  1255. * Answer whether protection is enabled or disabled
  1256. *
  1257. * @return true =&gt; protection enabled; false =&gt; protection disabled
  1258. */
  1259. @Override
  1260. public boolean getProtect() {
  1261. return isSheetLocked();
  1262. }
  1263. /**
  1264. * Enables sheet protection and sets the password for the sheet.
  1265. * Also sets some attributes on the {@link CTSheetProtection} that correspond to
  1266. * the default values used by Excel
  1267. *
  1268. * @param password to set for protection. Pass <code>null</code> to remove protection
  1269. */
  1270. @Override
  1271. public void protectSheet(String password) {
  1272. if (password != null) {
  1273. CTSheetProtection sheetProtection = safeGetProtectionField();
  1274. setSheetPassword(password, null); // defaults to xor password
  1275. sheetProtection.setSheet(true);
  1276. sheetProtection.setScenarios(true);
  1277. sheetProtection.setObjects(true);
  1278. } else {
  1279. worksheet.unsetSheetProtection();
  1280. }
  1281. }
  1282. /**
  1283. * Sets the sheet password.
  1284. *
  1285. * @param password if null, the password will be removed
  1286. * @param hashAlgo if null, the password will be set as XOR password (Excel 2010 and earlier)
  1287. * otherwise the given algorithm is used for calculating the hash password (Excel 2013)
  1288. */
  1289. public void setSheetPassword(String password, HashAlgorithm hashAlgo) {
  1290. if (password == null && !isSheetProtectionEnabled()) {
  1291. return;
  1292. }
  1293. setPassword(safeGetProtectionField(), password, hashAlgo, null);
  1294. }
  1295. /**
  1296. * Validate the password against the stored hash, the hashing method will be determined
  1297. * by the existing password attributes
  1298. * @return true, if the hashes match (... though original password may differ ...)
  1299. */
  1300. public boolean validateSheetPassword(String password) {
  1301. if (!isSheetProtectionEnabled()) {
  1302. return (password == null);
  1303. }
  1304. return validatePassword(safeGetProtectionField(), password, null);
  1305. }
  1306. /**
  1307. * Returns the logical row ( 0-based). If you ask for a row that is not
  1308. * defined you get a null. This is to say row 4 represents the fifth row on a sheet.
  1309. *
  1310. * @param rownum row to get
  1311. * @return <code>XSSFRow</code> representing the rownumber or <code>null</code> if its not defined on the sheet
  1312. */
  1313. @Override
  1314. public XSSFRow getRow(int rownum) {
  1315. // Performance optimization: explicit boxing is slightly faster than auto-unboxing, though may use more memory
  1316. //noinspection UnnecessaryBoxing
  1317. final Integer rownumI = Integer.valueOf(rownum); // NOSONAR
  1318. return _rows.get(rownumI);
  1319. }
  1320. /**
  1321. * returns all rows between startRow and endRow, inclusive.
  1322. * Rows between startRow and endRow that haven't been created are not included
  1323. * in result unless createRowIfMissing is true
  1324. *
  1325. * @param startRowNum the first row number in this sheet to return
  1326. * @param endRowNum the last row number in this sheet to return
  1327. * @param createRowIfMissing If missing rows should be created.
  1328. * @return All rows between startRow and endRow, inclusive. If createRowIfMissing is false,
  1329. * only previously existing rows are returned, otherwise empty rows are added as necessary
  1330. * @throws IllegalArgumentException if startRowNum and endRowNum are not in ascending order
  1331. */
  1332. private List<XSSFRow> getRows(int startRowNum, int endRowNum, boolean createRowIfMissing) {
  1333. if (startRowNum > endRowNum) {
  1334. throw new IllegalArgumentException("getRows: startRowNum must be less than or equal to endRowNum");
  1335. }
  1336. final List<XSSFRow> rows = new ArrayList<>();
  1337. if (createRowIfMissing) {
  1338. for (int i = startRowNum; i <= endRowNum; i++) {
  1339. XSSFRow row = getRow(i);
  1340. if (row == null) {
  1341. row = createRow(i);
  1342. }
  1343. rows.add(row);
  1344. }
  1345. }
  1346. else {
  1347. // Performance optimization: explicit boxing is slightly faster than auto-unboxing, though may use more memory
  1348. //noinspection UnnecessaryBoxing
  1349. final Integer startI = Integer.valueOf(startRowNum); // NOSONAR
  1350. //noinspection UnnecessaryBoxing
  1351. final Integer endI = Integer.valueOf(endRowNum+1); // NOSONAR
  1352. final Collection<XSSFRow> inclusive = _rows.subMap(startI, endI).values();
  1353. rows.addAll(inclusive);
  1354. }
  1355. return rows;
  1356. }
  1357. /**
  1358. * Horizontal page break information used for print layout view, page layout view, drawing print breaks in normal
  1359. * view, and for printing the worksheet.
  1360. *
  1361. * @return row indexes of all the horizontal page breaks, never <code>null</code>
  1362. */
  1363. @Override
  1364. public int[] getRowBreaks() {
  1365. return worksheet.isSetRowBreaks() ? getBreaks(worksheet.getRowBreaks()) : new int[0];
  1366. }
  1367. /**
  1368. * Flag indicating whether summary rows appear below detail in an outline, when applying an outline.
  1369. *
  1370. * <p>
  1371. * When true a summary row is inserted below the detailed data being summarized and a
  1372. * new outline level is established on that row.
  1373. * </p>
  1374. * <p>
  1375. * When false a summary row is inserted above the detailed data being summarized and a new outline level
  1376. * is established on that row.
  1377. * </p>
  1378. * @return <code>true</code> if row summaries appear below detail in the outline
  1379. */
  1380. @Override
  1381. public boolean getRowSumsBelow() {
  1382. CTSheetPr sheetPr = worksheet.getSheetPr();
  1383. CTOutlinePr outlinePr = (sheetPr != null && sheetPr.isSetOutlinePr())
  1384. ? sheetPr.getOutlinePr() : null;
  1385. return outlinePr == null || outlinePr.getSummaryBelow();
  1386. }
  1387. /**
  1388. * Flag indicating whether summary rows appear below detail in an outline, when applying an outline.
  1389. *
  1390. * <p>
  1391. * When true a summary row is inserted below the detailed data being summarized and a
  1392. * new outline level is established on that row.
  1393. * </p>
  1394. * <p>
  1395. * When false a summary row is inserted above the detailed data being summarized and a new outline level
  1396. * is established on that row.
  1397. * </p>
  1398. * @param value <code>true</code> if row summaries appear below detail in the outline
  1399. */
  1400. @Override
  1401. public void setRowSumsBelow(boolean value) {
  1402. ensureOutlinePr().setSummaryBelow(value);
  1403. }
  1404. /**
  1405. * Flag indicating whether summary columns appear to the right of detail in an outline, when applying an outline.
  1406. *
  1407. * <p>
  1408. * When true a summary column is inserted to the right of the detailed data being summarized
  1409. * and a new outline level is established on that column.
  1410. * </p>
  1411. * <p>
  1412. * When false a summary column is inserted to the left of the detailed data being
  1413. * summarized and a new outline level is established on that column.
  1414. * </p>
  1415. * @return <code>true</code> if col summaries appear right of the detail in the outline
  1416. */
  1417. @Override
  1418. public boolean getRowSumsRight() {
  1419. CTSheetPr sheetPr = worksheet.getSheetPr();
  1420. CTOutlinePr outlinePr = (sheetPr != null && sheetPr.isSetOutlinePr())
  1421. ? sheetPr.getOutlinePr() : CTOutlinePr.Factory.newInstance();
  1422. return outlinePr.getSummaryRight();
  1423. }
  1424. /**
  1425. * Flag indicating whether summary columns appear to the right of detail in an outline, when applying an outline.
  1426. *
  1427. * <p>
  1428. * When true a summary column is inserted to the right of the detailed data being summarized
  1429. * and a new outline level is established on that column.
  1430. * </p>
  1431. * <p>
  1432. * When false a summary column is inserted to the left of the detailed data being
  1433. * summarized and a new outline level is established on that column.
  1434. * </p>
  1435. * @param value <code>true</code> if col summaries appear right of the detail in the outline
  1436. */
  1437. @Override
  1438. public void setRowSumsRight(boolean value) {
  1439. ensureOutlinePr().setSummaryRight(value);
  1440. }
  1441. /**
  1442. * Ensure CTWorksheet.CTSheetPr.CTOutlinePr
  1443. */
  1444. private CTOutlinePr ensureOutlinePr(){
  1445. CTSheetPr sheetPr = worksheet.isSetSheetPr() ? worksheet.getSheetPr() : worksheet.addNewSheetPr();
  1446. return sheetPr.isSetOutlinePr() ? sheetPr.getOutlinePr() : sheetPr.addNewOutlinePr();
  1447. }
  1448. /**
  1449. * A flag indicating whether scenarios are locked when the sheet is protected.
  1450. *
  1451. * @return true =&gt; protection enabled; false =&gt; protection disabled
  1452. */
  1453. @Override
  1454. public boolean getScenarioProtect() {
  1455. return worksheet.isSetSheetProtection() && worksheet.getSheetProtection().getScenarios();
  1456. }
  1457. /**
  1458. * The top row in the visible view when the sheet is
  1459. * first viewed after opening it in a viewer
  1460. *
  1461. * @return integer indicating the rownum (0 based) of the top row
  1462. */
  1463. @Override
  1464. public short getTopRow() {
  1465. final CTSheetView dsv = getDefaultSheetView(false);
  1466. final String cellRef = (dsv == null) ? null : dsv.getTopLeftCell();
  1467. if(cellRef == null) {
  1468. return 0;
  1469. }
  1470. return (short) new CellReference(cellRef).getRow();
  1471. }
  1472. /**
  1473. * Determine whether printed output for this sheet will be vertically centered.
  1474. *
  1475. * @return whether printed output for this sheet will be vertically centered.
  1476. */
  1477. @Override
  1478. public boolean getVerticallyCenter() {
  1479. CTPrintOptions opts = worksheet.getPrintOptions();
  1480. return opts != null && opts.getVerticalCentered();
  1481. }
  1482. /**
  1483. * Group between (0 based) columns
  1484. */
  1485. @Override
  1486. public void groupColumn(int fromColumn, int toColumn) {
  1487. groupColumn1Based(fromColumn+1, toColumn+1);
  1488. }
  1489. private void groupColumn1Based(int fromColumn, int toColumn) {
  1490. CTCols ctCols=worksheet.getColsArray(0);
  1491. CTCol ctCol=CTCol.Factory.newInstance();
  1492. // copy attributes, as they might be removed by merging with the new column
  1493. // TODO: check if this fix is really necessary or if the sweeping algorithm
  1494. // in addCleanColIntoCols needs to be adapted ...
  1495. CTCol fixCol_before = this.columnHelper.getColumn1Based(toColumn, false);
  1496. if (fixCol_before != null) {
  1497. fixCol_before = (CTCol)fixCol_before.copy();
  1498. }
  1499. ctCol.setMin(fromColumn);
  1500. ctCol.setMax(toColumn);
  1501. this.columnHelper.addCleanColIntoCols(ctCols, ctCol);
  1502. CTCol fixCol_after = this.columnHelper.getColumn1Based(toColumn, false);
  1503. if (fixCol_before != null && fixCol_after != null) {
  1504. this.columnHelper.setColumnAttributes(fixCol_before, fixCol_after);
  1505. }
  1506. for(int index=fromColumn;index<=toColumn;index++){
  1507. CTCol col=columnHelper.getColumn1Based(index, false);
  1508. //col must exist
  1509. short outlineLevel=col.getOutlineLevel();
  1510. col.setOutlineLevel((short)(outlineLevel+1));
  1511. index = Math.toIntExact(col.getMax());
  1512. }
  1513. worksheet.setColsArray(0,ctCols);
  1514. setSheetFormatPrOutlineLevelCol();
  1515. }
  1516. /**
  1517. * Do not leave the width attribute undefined (see #52186).
  1518. */
  1519. private void setColWidthAttribute(CTCols ctCols) {
  1520. for (CTCol col : ctCols.getColArray()) {
  1521. if (!col.isSetWidth()) {
  1522. col.setWidth(getDefaultColumnWidth());
  1523. col.setCustomWidth(false);
  1524. }
  1525. }
  1526. }
  1527. /**
  1528. * Tie a range of cell together so that they can be collapsed or expanded
  1529. *
  1530. * @param fromRow start row (0-based)
  1531. * @param toRow end row (0-based)
  1532. */
  1533. @Override
  1534. public void groupRow(int fromRow, int toRow) {
  1535. for (int i = fromRow; i <= toRow; i++) {
  1536. XSSFRow xrow = getRow(i);
  1537. if (xrow == null) {
  1538. xrow = createRow(i);
  1539. }
  1540. CTRow ctrow = xrow.getCTRow();
  1541. short outlineLevel = ctrow.getOutlineLevel();
  1542. ctrow.setOutlineLevel((short) (outlineLevel + 1));
  1543. }
  1544. setSheetFormatPrOutlineLevelRow();
  1545. }
  1546. private short getMaxOutlineLevelRows(){
  1547. int outlineLevel = 0;
  1548. for (XSSFRow xrow : _rows.values()) {
  1549. outlineLevel = Math.max(outlineLevel, xrow.getCTRow().getOutlineLevel());
  1550. }
  1551. return (short) outlineLevel;
  1552. }
  1553. private short getMaxOutlineLevelCols() {
  1554. CTCols ctCols = worksheet.getColsArray(0);
  1555. int outlineLevel = 0;
  1556. for (CTCol col : ctCols.getColArray()) {
  1557. outlineLevel = Math.max(outlineLevel, col.getOutlineLevel());
  1558. }
  1559. return (short) outlineLevel;
  1560. }
  1561. /**
  1562. * Determines if there is a page break at the indicated column
  1563. */
  1564. @Override
  1565. public boolean isColumnBroken(int column) {
  1566. for (int colBreak : getColumnBreaks()) {
  1567. if (colBreak == column) {
  1568. return true;
  1569. }
  1570. }
  1571. return false;
  1572. }
  1573. /**
  1574. * Get the hidden state for a given column.
  1575. *
  1576. * @param columnIndex - the column to set (0-based)
  1577. * @return hidden - <code>false</code> if the column is visible
  1578. */
  1579. @Override
  1580. public boolean isColumnHidden(int columnIndex) {
  1581. CTCol col = columnHelper.getColumn(columnIndex, false);
  1582. return col != null && col.getHidden();
  1583. }
  1584. /**
  1585. * Gets the flag indicating whether this sheet should display formulas.
  1586. *
  1587. * @return <code>true</code> if this sheet should display formulas.
  1588. */
  1589. @Override
  1590. public boolean isDisplayFormulas() {
  1591. final CTSheetView dsv = getDefaultSheetView(false);
  1592. return dsv != null && dsv.getShowFormulas();
  1593. }
  1594. /**
  1595. * Gets the flag indicating whether this sheet displays the lines
  1596. * between rows and columns to make editing and reading easier.
  1597. *
  1598. * @return <code>true</code> (default) if this sheet displays gridlines.
  1599. * @see #isPrintGridlines() to check if printing of gridlines is turned on or off
  1600. */
  1601. @Override
  1602. public boolean isDisplayGridlines() {
  1603. final CTSheetView dsv = getDefaultSheetView(false);
  1604. return (dsv == null) || dsv.getShowGridLines();
  1605. }
  1606. /**
  1607. * Sets the flag indicating whether this sheet should display the lines
  1608. * between rows and columns to make editing and reading easier.
  1609. * To turn printing of gridlines use {@link #setPrintGridlines(boolean)}
  1610. *
  1611. *
  1612. * @param show <code>true</code> if this sheet should display gridlines.
  1613. * @see #setPrintGridlines(boolean)
  1614. */
  1615. @Override
  1616. public void setDisplayGridlines(boolean show) {
  1617. final CTSheetView dsv = getDefaultSheetView(true);
  1618. assert(dsv != null);
  1619. dsv.setShowGridLines(show);
  1620. }
  1621. /**
  1622. * Gets the flag indicating whether this sheet should display row and column headings.
  1623. * <p>
  1624. * Row heading are the row numbers to the side of the sheet
  1625. * </p>
  1626. * <p>
  1627. * Column heading are the letters or numbers that appear above the columns of the sheet
  1628. * </p>
  1629. *
  1630. * @return <code>true</code> (default) if this sheet should display row and column headings.
  1631. */
  1632. @Override
  1633. public boolean isDisplayRowColHeadings() {
  1634. final CTSheetView dsv = getDefaultSheetView(false);
  1635. return (dsv == null) || dsv.getShowRowColHeaders();
  1636. }
  1637. /**
  1638. * Sets the flag indicating whether this sheet should display row and column headings.
  1639. * <p>
  1640. * Row heading are the row numbers to the side of the sheet
  1641. * </p>
  1642. * <p>
  1643. * Column heading are the letters or numbers that appear above the columns of the sheet
  1644. * </p>
  1645. *
  1646. * @param show <code>true</code> if this sheet should display row and column headings.
  1647. */
  1648. @Override
  1649. public void setDisplayRowColHeadings(boolean show) {
  1650. final CTSheetView dsv = getDefaultSheetView(true);
  1651. assert(dsv != null);
  1652. dsv.setShowRowColHeaders(show);
  1653. }
  1654. /**
  1655. * Returns whether gridlines are printed.
  1656. *
  1657. * @return whether gridlines are printed
  1658. */
  1659. @Override
  1660. public boolean isPrintGridlines() {
  1661. CTPrintOptions opts = worksheet.getPrintOptions();
  1662. return opts != null && opts.getGridLines();
  1663. }
  1664. /**
  1665. * Turns on or off the printing of gridlines.
  1666. *
  1667. * @param value boolean to turn on or off the printing of gridlines
  1668. */
  1669. @Override
  1670. public void setPrintGridlines(boolean value) {
  1671. CTPrintOptions opts = worksheet.isSetPrintOptions() ?
  1672. worksheet.getPrintOptions() : worksheet.addNewPrintOptions();
  1673. opts.setGridLines(value);
  1674. }
  1675. /**
  1676. * Returns whether row and column headings are printed.
  1677. *
  1678. * @return whether row and column headings are printed
  1679. */
  1680. @Override
  1681. public boolean isPrintRowAndColumnHeadings() {
  1682. CTPrintOptions opts = worksheet.getPrintOptions();
  1683. return opts != null && opts.getHeadings();
  1684. }
  1685. /**
  1686. * Turns on or off the printing of row and column headings.
  1687. *
  1688. * @param value boolean to turn on or off the printing of row and column headings
  1689. */
  1690. @Override
  1691. public void setPrintRowAndColumnHeadings(boolean value) {
  1692. CTPrintOptions opts = worksheet.isSetPrintOptions() ?
  1693. worksheet.getPrintOptions() : worksheet.addNewPrintOptions();
  1694. opts.setHeadings(value);
  1695. }
  1696. /**
  1697. * Tests if there is a page break at the indicated row
  1698. *
  1699. * @param row index of the row to test
  1700. * @return <code>true</code> if there is a page break at the indicated row
  1701. */
  1702. @Override
  1703. public boolean isRowBroken(int row) {
  1704. for (int rowBreak : getRowBreaks()) {
  1705. if (rowBreak == row) {
  1706. return true;
  1707. }
  1708. }
  1709. return false;
  1710. }
  1711. private void setBreak(int id, CTPageBreak ctPgBreak, int lastIndex) {
  1712. CTBreak brk = ctPgBreak.addNewBrk();
  1713. // this is id of the element which is 1-based: <row r="1" ... >
  1714. brk.setId(id + 1L);
  1715. brk.setMan(true);
  1716. // end column of the break
  1717. brk.setMax(lastIndex);
  1718. int nPageBreaks = ctPgBreak.sizeOfBrkArray();
  1719. ctPgBreak.setCount(nPageBreaks);
  1720. ctPgBreak.setManualBreakCount(nPageBreaks);
  1721. }
  1722. /**
  1723. * Sets a page break at the indicated row
  1724. * Breaks occur above the specified row and left of the specified column inclusive.
  1725. *
  1726. * For example, <code>sheet.setColumnBreak(2);</code> breaks the sheet into two parts
  1727. * with columns A,B,C in the first and D,E,... in the second. Simuilar, <code>sheet.setRowBreak(2);</code>
  1728. * breaks the sheet into two parts with first three rows (rownum=1...3) in the first part
  1729. * and rows starting with rownum=4 in the second.
  1730. *
  1731. * @param row the row to break, inclusive
  1732. */
  1733. @Override
  1734. public void setRowBreak(int row) {
  1735. if (!isRowBroken(row)) {
  1736. CTPageBreak pgBreak = worksheet.isSetRowBreaks() ? worksheet.getRowBreaks() : worksheet.addNewRowBreaks();
  1737. setBreak(row, pgBreak, SpreadsheetVersion.EXCEL2007.getLastColumnIndex());
  1738. }
  1739. }
  1740. /**
  1741. * Removes a page break at the indicated column
  1742. */
  1743. @Override
  1744. public void removeColumnBreak(int column) {
  1745. if (worksheet.isSetColBreaks()) {
  1746. removeBreak(column, worksheet.getColBreaks());
  1747. } // else no breaks
  1748. }
  1749. /**
  1750. * Removes a merged region of cells (hence letting them free)
  1751. *
  1752. * @param index of the region to unmerge
  1753. */
  1754. @Override
  1755. public void removeMergedRegion(int index) {
  1756. if (!worksheet.isSetMergeCells()) {
  1757. return;
  1758. }
  1759. CTMergeCells ctMergeCells = worksheet.getMergeCells();
  1760. int size = ctMergeCells.sizeOfMergeCellArray();
  1761. assert(0 <= index && index < size);
  1762. if (size > 1) {
  1763. ctMergeCells.removeMergeCell(index);
  1764. } else {
  1765. worksheet.unsetMergeCells();
  1766. }
  1767. }
  1768. /**
  1769. * Removes a number of merged regions of cells (hence letting them free)
  1770. *
  1771. * This method can be used to bulk-remove merged regions in a way
  1772. * much faster than calling removeMergedRegion() for every single
  1773. * merged region.
  1774. *
  1775. * @param indices A set of the regions to unmerge
  1776. */
  1777. @Override
  1778. public void removeMergedRegions(Collection<Integer> indices) {
  1779. if (!worksheet.isSetMergeCells()) {
  1780. return;
  1781. }
  1782. CTMergeCells ctMergeCells = worksheet.getMergeCells();
  1783. List<CTMergeCell> newMergeCells = new ArrayList<>(ctMergeCells.sizeOfMergeCellArray());
  1784. int idx = 0;
  1785. for (CTMergeCell mc : ctMergeCells.getMergeCellArray()) {
  1786. if (!indices.contains(idx++)) {
  1787. newMergeCells.add(mc);
  1788. }
  1789. }
  1790. if (newMergeCells.isEmpty()) {
  1791. worksheet.unsetMergeCells();
  1792. } else {
  1793. CTMergeCell[] newMergeCellsArray = new CTMergeCell[newMergeCells.size()];
  1794. ctMergeCells.setMergeCellArray(newMergeCells.toArray(newMergeCellsArray));
  1795. }
  1796. }
  1797. /**
  1798. * Remove a row from this sheet. All cells contained in the row are removed as well
  1799. *
  1800. * @param row the row to remove.
  1801. */
  1802. @Override
  1803. public void removeRow(Row row) {
  1804. if (row.getSheet() != this) {
  1805. throw new IllegalArgumentException("Specified row does not belong to this sheet");
  1806. }
  1807. // collect cells into a temporary array to avoid ConcurrentModificationException
  1808. ArrayList<XSSFCell> cellsToDelete = new ArrayList<>();
  1809. for (Cell cell : row) {
  1810. cellsToDelete.add((XSSFCell)cell);
  1811. }
  1812. for (XSSFCell cell : cellsToDelete) {
  1813. row.removeCell(cell);
  1814. }
  1815. final int rowNum = row.getRowNum();
  1816. // Performance optimization: explicit boxing is slightly faster than auto-unboxing, though may use more memory
  1817. //noinspection UnnecessaryBoxing
  1818. final Integer rowNumI = Integer.valueOf(rowNum); // NOSONAR
  1819. // this is not the physical row number!
  1820. final int idx = _rows.headMap(rowNumI).size();
  1821. _rows.remove(rowNumI);
  1822. worksheet.getSheetData().removeRow(idx);
  1823. // also remove any comment located in that row
  1824. if(sheetComments != null) {
  1825. for (CellAddress ref : getCellComments().keySet()) {
  1826. if (ref.getRow() == rowNum) {
  1827. sheetComments.removeComment(ref);
  1828. }
  1829. }
  1830. }
  1831. }
  1832. /**
  1833. * Removes the page break at the indicated row
  1834. */
  1835. @Override
  1836. public void removeRowBreak(int row) {
  1837. if (worksheet.isSetRowBreaks()) {
  1838. removeBreak(row, worksheet.getRowBreaks());
  1839. } // else no breaks
  1840. }
  1841. /**
  1842. * Control if Excel should be asked to recalculate all formulas on this sheet
  1843. * when the workbook is opened.
  1844. *
  1845. * <p>
  1846. * Calculating the formula values with {@link org.apache.poi.ss.usermodel.FormulaEvaluator} is the
  1847. * recommended solution, but this may be used for certain cases where
  1848. * evaluation in POI is not possible.
  1849. * </p>
  1850. *
  1851. * <p>
  1852. * It is recommended to force recalcuation of formulas on workbook level using
  1853. * {@link org.apache.poi.ss.usermodel.Workbook#setForceFormulaRecalculation(boolean)}
  1854. * to ensure that all cross-worksheet formuals and external dependencies are updated.
  1855. * </p>
  1856. * @param value true if the application will perform a full recalculation of
  1857. * this worksheet values when the workbook is opened
  1858. *
  1859. * @see org.apache.poi.ss.usermodel.Workbook#setForceFormulaRecalculation(boolean)
  1860. */
  1861. @Override
  1862. public void setForceFormulaRecalculation(boolean value) {
  1863. CTCalcPr calcPr = getWorkbook().getCTWorkbook().getCalcPr();
  1864. if(worksheet.isSetSheetCalcPr()) {
  1865. // Change the current setting
  1866. CTSheetCalcPr calc = worksheet.getSheetCalcPr();
  1867. calc.setFullCalcOnLoad(value);
  1868. }
  1869. else if(value) {
  1870. // Add the Calc block and set it
  1871. CTSheetCalcPr calc = worksheet.addNewSheetCalcPr();
  1872. calc.setFullCalcOnLoad(value);
  1873. }
  1874. if(value && calcPr != null && calcPr.getCalcMode() == STCalcMode.MANUAL) {
  1875. calcPr.setCalcMode(STCalcMode.AUTO);
  1876. }
  1877. }
  1878. /**
  1879. * Whether Excel will be asked to recalculate all formulas of this sheet
  1880. * when the workbook is opened.
  1881. *
  1882. * Note: This just returns if the sheet has the recalculate flag set and
  1883. * will still return false even if recalculation is enabled on workbook-level.
  1884. *
  1885. * @return true if the Sheet has the recalculate-flag set.
  1886. */
  1887. @Override
  1888. public boolean getForceFormulaRecalculation() {
  1889. if(worksheet.isSetSheetCalcPr()) {
  1890. CTSheetCalcPr calc = worksheet.getSheetCalcPr();
  1891. return calc.getFullCalcOnLoad();
  1892. }
  1893. return false;
  1894. }
  1895. /**
  1896. * @return an iterator of the PHYSICAL rows. Meaning the 3rd element may not
  1897. * be the third row if say for instance the second row is undefined.
  1898. * Call getRowNum() on each row if you care which one it is.
  1899. */
  1900. @Override
  1901. @SuppressWarnings("unchecked")
  1902. public Iterator<Row> rowIterator() {
  1903. return (Iterator<Row>)(Iterator<? extends Row>) _rows.values().iterator();
  1904. }
  1905. /**
  1906. * Alias for {@link #rowIterator()} to
  1907. * allow foreach loops
  1908. */
  1909. @Override
  1910. public Iterator<Row> iterator() {
  1911. return rowIterator();
  1912. }
  1913. /**
  1914. * Flag indicating whether the sheet displays Automatic Page Breaks.
  1915. *
  1916. * @return <code>true</code> if the sheet displays Automatic Page Breaks.
  1917. */
  1918. @Override
  1919. public boolean getAutobreaks() {
  1920. CTSheetPr sheetPr = getSheetTypeSheetPr();
  1921. CTPageSetUpPr psSetup = (sheetPr == null || !sheetPr.isSetPageSetUpPr()) ?
  1922. CTPageSetUpPr.Factory.newInstance() : sheetPr.getPageSetUpPr();
  1923. return psSetup.getAutoPageBreaks();
  1924. }
  1925. /**
  1926. * Flag indicating whether the sheet displays Automatic Page Breaks.
  1927. *
  1928. * @param value <code>true</code> if the sheet displays Automatic Page Breaks.
  1929. */
  1930. @Override
  1931. public void setAutobreaks(boolean value) {
  1932. CTSheetPr sheetPr = getSheetTypeSheetPr();
  1933. CTPageSetUpPr psSetup = sheetPr.isSetPageSetUpPr() ? sheetPr.getPageSetUpPr() : sheetPr.addNewPageSetUpPr();
  1934. psSetup.setAutoPageBreaks(value);
  1935. }
  1936. /**
  1937. * Sets a page break at the indicated column.
  1938. * Breaks occur above the specified row and left of the specified column inclusive.
  1939. *
  1940. * For example, <code>sheet.setColumnBreak(2);</code> breaks the sheet into two parts
  1941. * with columns A,B,C in the first and D,E,... in the second. Simuilar, <code>sheet.setRowBreak(2);</code>
  1942. * breaks the sheet into two parts with first three rows (rownum=1...3) in the first part
  1943. * and rows starting with rownum=4 in the second.
  1944. *
  1945. * @param column the column to break, inclusive
  1946. */
  1947. @Override
  1948. public void setColumnBreak(int column) {
  1949. if (!isColumnBroken(column)) {
  1950. CTPageBreak pgBreak = worksheet.isSetColBreaks() ? worksheet.getColBreaks() : worksheet.addNewColBreaks();
  1951. setBreak(column, pgBreak, SpreadsheetVersion.EXCEL2007.getLastRowIndex());
  1952. }
  1953. }
  1954. @Override
  1955. public void setColumnGroupCollapsed(int columnNumber, boolean collapsed) {
  1956. if (collapsed) {
  1957. collapseColumn(columnNumber);
  1958. } else {
  1959. expandColumn(columnNumber);
  1960. }
  1961. }
  1962. private void collapseColumn(int columnNumber) {
  1963. CTCols cols = worksheet.getColsArray(0);
  1964. CTCol col = columnHelper.getColumn(columnNumber, false);
  1965. int colInfoIx = columnHelper.getIndexOfColumn(cols, col);
  1966. if (colInfoIx == -1) {
  1967. return;
  1968. }
  1969. // Find the start of the group.
  1970. int groupStartColInfoIx = findStartOfColumnOutlineGroup(colInfoIx);
  1971. CTCol columnInfo = cols.getColArray(groupStartColInfoIx);
  1972. // Hide all the columns until the end of the group
  1973. int lastColMax = setGroupHidden(groupStartColInfoIx, columnInfo
  1974. .getOutlineLevel(), true);
  1975. // write collapse field
  1976. setColumn(lastColMax + 1, 0, null, null, Boolean.TRUE);
  1977. }
  1978. private void setColumn(int targetColumnIx, Integer style,
  1979. Integer level, Boolean hidden, Boolean collapsed) {
  1980. CTCols cols = worksheet.getColsArray(0);
  1981. CTCol ci = null;
  1982. for (CTCol tci : cols.getColArray()) {
  1983. long tciMin = tci.getMin();
  1984. long tciMax = tci.getMax();
  1985. if (tciMin >= targetColumnIx && tciMax <= targetColumnIx) {
  1986. ci = tci;
  1987. break;
  1988. }
  1989. if (tciMin > targetColumnIx) {
  1990. // call column infos after k are for later columns
  1991. break; // exit now so k will be the correct insert pos
  1992. }
  1993. }
  1994. if (ci == null) {
  1995. // okay so there ISN'T a column info record that covers this column
  1996. // so lets create one!
  1997. CTCol nci = CTCol.Factory.newInstance();
  1998. nci.setMin(targetColumnIx);
  1999. nci.setMax(targetColumnIx);
  2000. unsetCollapsed(collapsed, nci);
  2001. this.columnHelper.addCleanColIntoCols(cols, nci);
  2002. return;
  2003. }
  2004. boolean styleChanged = style != null && ci.getStyle() != style;
  2005. boolean levelChanged = level != null && ci.getOutlineLevel() != level;
  2006. boolean hiddenChanged = hidden != null && ci.getHidden() != hidden;
  2007. boolean collapsedChanged = collapsed != null && ci.getCollapsed() != collapsed;
  2008. boolean columnChanged = levelChanged || hiddenChanged || collapsedChanged || styleChanged;
  2009. if (!columnChanged) {
  2010. // do nothing...nothing changed.
  2011. return;
  2012. }
  2013. long ciMin = ci.getMin();
  2014. long ciMax = ci.getMax();
  2015. if (ciMin == targetColumnIx && ciMax == targetColumnIx) {
  2016. // ColumnInfo ci for a single column, the target column
  2017. unsetCollapsed(collapsed, ci);
  2018. return;
  2019. }
  2020. if (ciMin == targetColumnIx || ciMax == targetColumnIx) {
  2021. // The target column is at either end of the multi-column ColumnInfo ci
  2022. // we'll just divide the info and create a new one
  2023. if (ciMin == targetColumnIx) {
  2024. ci.setMin(targetColumnIx + 1L);
  2025. } else {
  2026. ci.setMax(targetColumnIx - 1L);
  2027. }
  2028. CTCol nci = columnHelper.cloneCol(cols, ci);
  2029. nci.setMin(targetColumnIx);
  2030. unsetCollapsed(collapsed, nci);
  2031. this.columnHelper.addCleanColIntoCols(cols, nci);
  2032. } else {
  2033. // split to 3 records
  2034. CTCol ciMid = columnHelper.cloneCol(cols, ci);
  2035. CTCol ciEnd = columnHelper.cloneCol(cols, ci);
  2036. int lastcolumn = Math.toIntExact(ciMax);
  2037. ci.setMax(targetColumnIx - 1L);
  2038. ciMid.setMin(targetColumnIx);
  2039. ciMid.setMax(targetColumnIx);
  2040. unsetCollapsed(collapsed, ciMid);
  2041. this.columnHelper.addCleanColIntoCols(cols, ciMid);
  2042. ciEnd.setMin(targetColumnIx + 1L);
  2043. ciEnd.setMax(lastcolumn);
  2044. this.columnHelper.addCleanColIntoCols(cols, ciEnd);
  2045. }
  2046. }
  2047. private void unsetCollapsed(Boolean collapsed, CTCol ci) {
  2048. if (collapsed != null && collapsed) {
  2049. ci.setCollapsed(true);
  2050. } else {
  2051. ci.unsetCollapsed();
  2052. }
  2053. }
  2054. /**
  2055. * Sets all adjacent columns of the same outline level to the specified
  2056. * hidden status.
  2057. *
  2058. * @param pIdx
  2059. * the col info index of the start of the outline group
  2060. * @return the column index of the last column in the outline group
  2061. */
  2062. private int setGroupHidden(int pIdx, int level, boolean hidden) {
  2063. CTCols cols = worksheet.getColsArray(0);
  2064. int idx = pIdx;
  2065. CTCol[] colArray = cols.getColArray();
  2066. CTCol columnInfo = colArray[idx];
  2067. while (idx < colArray.length) {
  2068. columnInfo.setHidden(hidden);
  2069. if (idx + 1 < colArray.length) {
  2070. CTCol nextColumnInfo = colArray[idx + 1];
  2071. if (!isAdjacentBefore(columnInfo, nextColumnInfo)) {
  2072. break;
  2073. }
  2074. if (nextColumnInfo.getOutlineLevel() < level) {
  2075. break;
  2076. }
  2077. columnInfo = nextColumnInfo;
  2078. }
  2079. idx++;
  2080. }
  2081. return Math.toIntExact(columnInfo.getMax());
  2082. }
  2083. private boolean isAdjacentBefore(CTCol col, CTCol otherCol) {
  2084. return col.getMax() == otherCol.getMin() - 1;
  2085. }
  2086. private int findStartOfColumnOutlineGroup(int pIdx) {
  2087. // Find the start of the group.
  2088. CTCols cols = worksheet.getColsArray(0);
  2089. CTCol[] colArray = cols.getColArray();
  2090. CTCol columnInfo = colArray[pIdx];
  2091. int level = columnInfo.getOutlineLevel();
  2092. int idx = pIdx;
  2093. while (idx != 0) {
  2094. CTCol prevColumnInfo = colArray[idx - 1];
  2095. if (!isAdjacentBefore(prevColumnInfo, columnInfo)) {
  2096. break;
  2097. }
  2098. if (prevColumnInfo.getOutlineLevel() < level) {
  2099. break;
  2100. }
  2101. idx--;
  2102. columnInfo = prevColumnInfo;
  2103. }
  2104. return idx;
  2105. }
  2106. private int findEndOfColumnOutlineGroup(int colInfoIndex) {
  2107. CTCols cols = worksheet.getColsArray(0);
  2108. // Find the end of the group.
  2109. CTCol[] colArray = cols.getColArray();
  2110. CTCol columnInfo = colArray[colInfoIndex];
  2111. int level = columnInfo.getOutlineLevel();
  2112. int idx = colInfoIndex;
  2113. int lastIdx = colArray.length - 1;
  2114. while (idx < lastIdx) {
  2115. CTCol nextColumnInfo = colArray[idx + 1];
  2116. if (!isAdjacentBefore(columnInfo, nextColumnInfo)) {
  2117. break;
  2118. }
  2119. if (nextColumnInfo.getOutlineLevel() < level) {
  2120. break;
  2121. }
  2122. idx++;
  2123. columnInfo = nextColumnInfo;
  2124. }
  2125. return idx;
  2126. }
  2127. private void expandColumn(int columnIndex) {
  2128. CTCols cols = worksheet.getColsArray(0);
  2129. CTCol col = columnHelper.getColumn(columnIndex, false);
  2130. int colInfoIx = columnHelper.getIndexOfColumn(cols, col);
  2131. int idx = findColInfoIdx(Math.toIntExact(col.getMax()), colInfoIx);
  2132. if (idx == -1) {
  2133. return;
  2134. }
  2135. // If it is already expanded do nothing.
  2136. if (!isColumnGroupCollapsed(idx)) {
  2137. return;
  2138. }
  2139. // Find the start/end of the group.
  2140. int startIdx = findStartOfColumnOutlineGroup(idx);
  2141. int endIdx = findEndOfColumnOutlineGroup(idx);
  2142. // expand:
  2143. // colapsed bit must be unset
  2144. // hidden bit gets unset _if_ surrounding groups are expanded you can
  2145. // determine
  2146. // this by looking at the hidden bit of the enclosing group. You will
  2147. // have
  2148. // to look at the start and the end of the current group to determine
  2149. // which
  2150. // is the enclosing group
  2151. // hidden bit only is altered for this outline level. ie. don't
  2152. // uncollapse contained groups
  2153. CTCol[] colArray = cols.getColArray();
  2154. CTCol columnInfo = colArray[endIdx];
  2155. if (!isColumnGroupHiddenByParent(idx)) {
  2156. short outlineLevel = columnInfo.getOutlineLevel();
  2157. boolean nestedGroup = false;
  2158. for (int i = startIdx; i <= endIdx; i++) {
  2159. CTCol ci = colArray[i];
  2160. if (outlineLevel == ci.getOutlineLevel()) {
  2161. ci.unsetHidden();
  2162. if (nestedGroup) {
  2163. nestedGroup = false;
  2164. ci.setCollapsed(true);
  2165. }
  2166. } else {
  2167. nestedGroup = true;
  2168. }
  2169. }
  2170. }
  2171. // Write collapse flag (stored in a single col info record after this
  2172. // outline group)
  2173. setColumn(Math.toIntExact(columnInfo.getMax() + 1), null, null,
  2174. Boolean.FALSE, Boolean.FALSE);
  2175. }
  2176. private boolean isColumnGroupHiddenByParent(int idx) {
  2177. CTCols cols = worksheet.getColsArray(0);
  2178. // Look out outline details of end
  2179. int endLevel = 0;
  2180. boolean endHidden = false;
  2181. int endOfOutlineGroupIdx = findEndOfColumnOutlineGroup(idx);
  2182. CTCol[] colArray = cols.getColArray();
  2183. if (endOfOutlineGroupIdx < (colArray.length - 1)) {
  2184. CTCol nextInfo = colArray[endOfOutlineGroupIdx + 1];
  2185. if (isAdjacentBefore(colArray[endOfOutlineGroupIdx], nextInfo)) {
  2186. endLevel = nextInfo.getOutlineLevel();
  2187. endHidden = nextInfo.getHidden();
  2188. }
  2189. }
  2190. // Look out outline details of start
  2191. int startLevel = 0;
  2192. boolean startHidden = false;
  2193. int startOfOutlineGroupIdx = findStartOfColumnOutlineGroup(idx);
  2194. if (startOfOutlineGroupIdx > 0) {
  2195. CTCol prevInfo = colArray[startOfOutlineGroupIdx - 1];
  2196. if (isAdjacentBefore(prevInfo, colArray[startOfOutlineGroupIdx])) {
  2197. startLevel = prevInfo.getOutlineLevel();
  2198. startHidden = prevInfo.getHidden();
  2199. }
  2200. }
  2201. if (endLevel > startLevel) {
  2202. return endHidden;
  2203. }
  2204. return startHidden;
  2205. }
  2206. private int findColInfoIdx(int columnValue, int fromColInfoIdx) {
  2207. CTCols cols = worksheet.getColsArray(0);
  2208. if (columnValue < 0) {
  2209. throw new IllegalArgumentException(
  2210. "column parameter out of range: " + columnValue);
  2211. }
  2212. if (fromColInfoIdx < 0) {
  2213. throw new IllegalArgumentException(
  2214. "fromIdx parameter out of range: " + fromColInfoIdx);
  2215. }
  2216. CTCol[] colArray = cols.getColArray();
  2217. for (int k = fromColInfoIdx; k < colArray.length; k++) {
  2218. CTCol ci = colArray[k];
  2219. if (containsColumn(ci, columnValue)) {
  2220. return k;
  2221. }
  2222. if (ci.getMin() > fromColInfoIdx) {
  2223. break;
  2224. }
  2225. }
  2226. return -1;
  2227. }
  2228. private boolean containsColumn(CTCol col, int columnIndex) {
  2229. return col.getMin() <= columnIndex && columnIndex <= col.getMax();
  2230. }
  2231. /**
  2232. * 'Collapsed' state is stored in a single column col info record
  2233. * immediately after the outline group
  2234. *
  2235. * @param idx The column-index to check
  2236. * @return a boolean represented if the column is collapsed
  2237. */
  2238. private boolean isColumnGroupCollapsed(int idx) {
  2239. CTCols cols = worksheet.getColsArray(0);
  2240. CTCol[] colArray = cols.getColArray();
  2241. int endOfOutlineGroupIdx = findEndOfColumnOutlineGroup(idx);
  2242. int nextColInfoIx = endOfOutlineGroupIdx + 1;
  2243. if (nextColInfoIx >= colArray.length) {
  2244. return false;
  2245. }
  2246. CTCol nextColInfo = colArray[nextColInfoIx];
  2247. CTCol col = colArray[endOfOutlineGroupIdx];
  2248. if (!isAdjacentBefore(col, nextColInfo)) {
  2249. return false;
  2250. }
  2251. return nextColInfo.getCollapsed();
  2252. }
  2253. /**
  2254. * Get the visibility state for a given column.
  2255. *
  2256. * @param columnIndex - the column to get (0-based)
  2257. * @param hidden - the visiblity state of the column
  2258. */
  2259. @Override
  2260. public void setColumnHidden(int columnIndex, boolean hidden) {
  2261. columnHelper.setColHidden(columnIndex, hidden);
  2262. }
  2263. /**
  2264. * Set the width (in units of 1/256th of a character width)
  2265. *
  2266. * <p>
  2267. * The maximum column width for an individual cell is 255 characters.
  2268. * This value represents the number of characters that can be displayed
  2269. * in a cell that is formatted with the standard font (first font in the workbook).
  2270. * </p>
  2271. *
  2272. * <p>
  2273. * Character width is defined as the maximum digit width
  2274. * of the numbers <code>0, 1, 2, ... 9</code> as rendered
  2275. * using the default font (first font in the workbook).
  2276. * <br>
  2277. * Unless you are using a very special font, the default character is '0' (zero),
  2278. * this is true for Arial (default font font in HSSF) and Calibri (default font in XSSF)
  2279. * </p>
  2280. *
  2281. * <p>
  2282. * Please note, that the width set by this method includes 4 pixels of margin padding (two on each side),
  2283. * plus 1 pixel padding for the gridlines (Section 3.3.1.12 of the OOXML spec).
  2284. * This results is a slightly less value of visible characters than passed to this method (approx. 1/2 of a character).
  2285. * </p>
  2286. * <p>
  2287. * To compute the actual number of visible characters,
  2288. * Excel uses the following formula (Section 3.3.1.12 of the OOXML spec):
  2289. * </p>
  2290. * <code>
  2291. * width = Truncate([{Number of Visible Characters} *
  2292. * {Maximum Digit Width} + {5 pixel padding}]/{Maximum Digit Width}*256)/256
  2293. * </code>
  2294. * <p>Using the Calibri font as an example, the maximum digit width of 11 point font size is 7 pixels (at 96 dpi).
  2295. * If you set a column width to be eight characters wide, e.g. <code>setColumnWidth(columnIndex, 8*256)</code>,
  2296. * then the actual value of visible characters (the value shown in Excel) is derived from the following equation:
  2297. * <code>
  2298. Truncate([numChars*7+5]/7*256)/256 = 8;
  2299. * </code>
  2300. *
  2301. * which gives <code>7.29</code>.
  2302. *
  2303. * @param columnIndex - the column to set (0-based)
  2304. * @param width - the width in units of 1/256th of a character width
  2305. * @throws IllegalArgumentException if width &gt; 255*256 (the maximum column width in Excel is 255 characters)
  2306. */
  2307. @Override
  2308. public void setColumnWidth(int columnIndex, int width) {
  2309. if(width > 255*256) {
  2310. throw new IllegalArgumentException("The maximum column width for an individual cell is 255 characters.");
  2311. }
  2312. columnHelper.setColWidth(columnIndex, (double)width/256);
  2313. columnHelper.setCustomWidth(columnIndex, true);
  2314. }
  2315. @Override
  2316. public void setDefaultColumnStyle(int column, CellStyle style) {
  2317. columnHelper.setColDefaultStyle(column, style);
  2318. }
  2319. /**
  2320. * Specifies the number of characters of the maximum digit width of the normal style's font.
  2321. * This value does not include margin padding or extra padding for gridlines. It is only the
  2322. * number of characters.
  2323. *
  2324. * @param width the number of characters. Default value is <code>8</code>.
  2325. */
  2326. @Override
  2327. public void setDefaultColumnWidth(int width) {
  2328. getSheetTypeSheetFormatPr().setBaseColWidth(width);
  2329. }
  2330. /**
  2331. * Set the default row height for the sheet (if the rows do not define their own height) in
  2332. * twips (1/20 of a point)
  2333. *
  2334. * @param height default row height in twips (1/20 of a point)
  2335. */
  2336. @Override
  2337. public void setDefaultRowHeight(short height) {
  2338. setDefaultRowHeightInPoints((float)height / Font.TWIPS_PER_POINT);
  2339. }
  2340. /**
  2341. * Sets default row height measured in point size.
  2342. *
  2343. * @param height default row height measured in point size.
  2344. */
  2345. @Override
  2346. public void setDefaultRowHeightInPoints(float height) {
  2347. CTSheetFormatPr pr = getSheetTypeSheetFormatPr();
  2348. pr.setDefaultRowHeight(height);
  2349. pr.setCustomHeight(true);
  2350. }
  2351. /**
  2352. * Sets the flag indicating whether this sheet should display formulas.
  2353. *
  2354. * @param show <code>true</code> if this sheet should display formulas.
  2355. */
  2356. @Override
  2357. public void setDisplayFormulas(boolean show) {
  2358. final CTSheetView dsv = getDefaultSheetView(true);
  2359. assert(dsv != null);
  2360. dsv.setShowFormulas(show);
  2361. }
  2362. /**
  2363. * Flag indicating whether the Fit to Page print option is enabled.
  2364. *
  2365. * @param b <code>true</code> if the Fit to Page print option is enabled.
  2366. */
  2367. @Override
  2368. public void setFitToPage(boolean b) {
  2369. getSheetTypePageSetUpPr().setFitToPage(b);
  2370. }
  2371. /**
  2372. * Center on page horizontally when printing.
  2373. *
  2374. * @param value whether to center on page horizontally when printing.
  2375. */
  2376. @Override
  2377. public void setHorizontallyCenter(boolean value) {
  2378. CTPrintOptions opts = worksheet.isSetPrintOptions() ?
  2379. worksheet.getPrintOptions() : worksheet.addNewPrintOptions();
  2380. opts.setHorizontalCentered(value);
  2381. }
  2382. /**
  2383. * Whether the output is vertically centered on the page.
  2384. *
  2385. * @param value true to vertically center, false otherwise.
  2386. */
  2387. @Override
  2388. public void setVerticallyCenter(boolean value) {
  2389. CTPrintOptions opts = worksheet.isSetPrintOptions() ?
  2390. worksheet.getPrintOptions() : worksheet.addNewPrintOptions();
  2391. opts.setVerticalCentered(value);
  2392. }
  2393. /**
  2394. * group the row It is possible for collapsed to be false and yet still have
  2395. * the rows in question hidden. This can be achieved by having a lower
  2396. * outline level collapsed, thus hiding all the child rows. Note that in
  2397. * this case, if the lowest level were expanded, the middle level would
  2398. * remain collapsed.
  2399. *
  2400. * @param rowIndex -
  2401. * the row involved, 0 based
  2402. * @param collapse -
  2403. * boolean value for collapse
  2404. */
  2405. @Override
  2406. public void setRowGroupCollapsed(int rowIndex, boolean collapse) {
  2407. if (collapse) {
  2408. collapseRow(rowIndex);
  2409. } else {
  2410. expandRow(rowIndex);
  2411. }
  2412. }
  2413. /**
  2414. * @param rowIndex the zero based row index to collapse
  2415. */
  2416. private void collapseRow(int rowIndex) {
  2417. XSSFRow row = getRow(rowIndex);
  2418. if (row != null) {
  2419. int startRow = findStartOfRowOutlineGroup(rowIndex);
  2420. // Hide all the columns until the end of the group
  2421. int lastRow = writeHidden(row, startRow, true);
  2422. if (getRow(lastRow) != null) {
  2423. getRow(lastRow).getCTRow().setCollapsed(true);
  2424. } else {
  2425. XSSFRow newRow = createRow(lastRow);
  2426. newRow.getCTRow().setCollapsed(true);
  2427. }
  2428. }
  2429. }
  2430. /**
  2431. * @param rowIndex the zero based row index to find from
  2432. */
  2433. private int findStartOfRowOutlineGroup(int rowIndex) {
  2434. // Find the start of the group.
  2435. short level = getRow(rowIndex).getCTRow().getOutlineLevel();
  2436. int currentRow = rowIndex;
  2437. while (getRow(currentRow) != null) {
  2438. if (getRow(currentRow).getCTRow().getOutlineLevel() < level) {
  2439. return currentRow + 1;
  2440. }
  2441. currentRow--;
  2442. }
  2443. return currentRow;
  2444. }
  2445. private int writeHidden(XSSFRow xRow, int rowIndex, boolean hidden) {
  2446. short level = xRow.getCTRow().getOutlineLevel();
  2447. for (Iterator<Row> it = rowIterator(); it.hasNext();) {
  2448. xRow = (XSSFRow) it.next();
  2449. // skip rows before the start of this group
  2450. if(xRow.getRowNum() < rowIndex) {
  2451. continue;
  2452. }
  2453. if (xRow.getCTRow().getOutlineLevel() >= level) {
  2454. xRow.getCTRow().setHidden(hidden);
  2455. rowIndex++;
  2456. }
  2457. }
  2458. return rowIndex;
  2459. }
  2460. /**
  2461. * @param rowNumber the zero based row index to expand
  2462. */
  2463. private void expandRow(int rowNumber) {
  2464. if (rowNumber == -1) {
  2465. return;
  2466. }
  2467. XSSFRow row = getRow(rowNumber);
  2468. // If it is already expanded do nothing.
  2469. if (!row.getCTRow().isSetHidden()) {
  2470. return;
  2471. }
  2472. // Find the start of the group.
  2473. int startIdx = findStartOfRowOutlineGroup(rowNumber);
  2474. // Find the end of the group.
  2475. int endIdx = findEndOfRowOutlineGroup(rowNumber);
  2476. // expand:
  2477. // collapsed must be unset
  2478. // hidden bit gets unset _if_ surrounding groups are expanded you can
  2479. // determine
  2480. // this by looking at the hidden bit of the enclosing group. You will
  2481. // have
  2482. // to look at the start and the end of the current group to determine
  2483. // which
  2484. // is the enclosing group
  2485. // hidden bit only is altered for this outline level. ie. don't
  2486. // un-collapse contained groups
  2487. short level = row.getCTRow().getOutlineLevel();
  2488. if (!isRowGroupHiddenByParent(rowNumber)) {
  2489. for (int i = startIdx; i < endIdx; i++) {
  2490. if (level == getRow(i).getCTRow().getOutlineLevel()) {
  2491. getRow(i).getCTRow().unsetHidden();
  2492. } else if (!isRowGroupCollapsed(i)) {
  2493. getRow(i).getCTRow().unsetHidden();
  2494. }
  2495. }
  2496. }
  2497. // Write collapse field
  2498. CTRow ctRow = getRow(endIdx).getCTRow();
  2499. // This avoids an IndexOutOfBounds if multiple nested groups are collapsed/expanded
  2500. if(ctRow.getCollapsed()) {
  2501. ctRow.unsetCollapsed();
  2502. }
  2503. }
  2504. /**
  2505. * @param row the zero based row index to find from
  2506. */
  2507. public int findEndOfRowOutlineGroup(int row) {
  2508. short level = getRow(row).getCTRow().getOutlineLevel();
  2509. int currentRow;
  2510. final int lastRowNum = getLastRowNum();
  2511. for (currentRow = row; currentRow < lastRowNum; currentRow++) {
  2512. if (getRow(currentRow) == null
  2513. || getRow(currentRow).getCTRow().getOutlineLevel() < level) {
  2514. break;
  2515. }
  2516. }
  2517. return currentRow;
  2518. }
  2519. /**
  2520. * @param row the zero based row index to find from
  2521. */
  2522. private boolean isRowGroupHiddenByParent(int row) {
  2523. // Look out outline details of end
  2524. int endLevel;
  2525. boolean endHidden;
  2526. int endOfOutlineGroupIdx = findEndOfRowOutlineGroup(row);
  2527. if (getRow(endOfOutlineGroupIdx) == null) {
  2528. endLevel = 0;
  2529. endHidden = false;
  2530. } else {
  2531. endLevel = getRow(endOfOutlineGroupIdx).getCTRow().getOutlineLevel();
  2532. endHidden = getRow(endOfOutlineGroupIdx).getCTRow().getHidden();
  2533. }
  2534. // Look out outline details of start
  2535. int startLevel;
  2536. boolean startHidden;
  2537. int startOfOutlineGroupIdx = findStartOfRowOutlineGroup(row);
  2538. if (startOfOutlineGroupIdx < 0
  2539. || getRow(startOfOutlineGroupIdx) == null) {
  2540. startLevel = 0;
  2541. startHidden = false;
  2542. } else {
  2543. startLevel = getRow(startOfOutlineGroupIdx).getCTRow()
  2544. .getOutlineLevel();
  2545. startHidden = getRow(startOfOutlineGroupIdx).getCTRow()
  2546. .getHidden();
  2547. }
  2548. if (endLevel > startLevel) {
  2549. return endHidden;
  2550. }
  2551. return startHidden;
  2552. }
  2553. /**
  2554. * @param row the zero based row index to find from
  2555. */
  2556. private boolean isRowGroupCollapsed(int row) {
  2557. int collapseRow = findEndOfRowOutlineGroup(row) + 1;
  2558. if (getRow(collapseRow) == null) {
  2559. return false;
  2560. }
  2561. return getRow(collapseRow).getCTRow().getCollapsed();
  2562. }
  2563. /**
  2564. * Window zoom magnification for current view representing percent values.
  2565. * Valid values range from 10 to 400. Horizontal &amp; Vertical scale together.
  2566. *
  2567. * For example:
  2568. * <pre>
  2569. * 10 - 10%
  2570. * 20 - 20%
  2571. * ...
  2572. * 100 - 100%
  2573. * ...
  2574. * 400 - 400%
  2575. * </pre>
  2576. *
  2577. * Current view can be Normal, Page Layout, or Page Break Preview.
  2578. *
  2579. * @param scale window zoom magnification
  2580. * @throws IllegalArgumentException if scale is invalid
  2581. */
  2582. @Override
  2583. public void setZoom(int scale) {
  2584. if (scale < 10 || scale > 400) {
  2585. throw new IllegalArgumentException("Valid scale values range from 10 to 400");
  2586. }
  2587. final CTSheetView dsv = getDefaultSheetView(true);
  2588. assert(dsv != null);
  2589. dsv.setZoomScale(scale);
  2590. }
  2591. /**
  2592. * copyRows rows from srcRows to this sheet starting at destStartRow
  2593. *
  2594. * Additionally copies merged regions that are completely defined in these
  2595. * rows (ie. merged 2 cells on a row to be shifted).
  2596. * @param srcRows the rows to copy. Formulas will be offset by the difference
  2597. * in the row number of the first row in srcRows and destStartRow (even if srcRows
  2598. * are from a different sheet).
  2599. * @param destStartRow the row in this sheet to paste the first row of srcRows
  2600. * the remainder of srcRows will be pasted below destStartRow per the cell copy policy
  2601. * @param policy is the cell copy policy, which can be used to merge the source and destination
  2602. * when the source is blank, copy styles only, paste as value, etc
  2603. */
  2604. @Beta
  2605. public void copyRows(List<? extends Row> srcRows, int destStartRow, CellCopyPolicy policy) {
  2606. if (srcRows == null || srcRows.size() == 0) {
  2607. throw new IllegalArgumentException("No rows to copy");
  2608. }
  2609. final Row srcStartRow = srcRows.get(0);
  2610. final Row srcEndRow = srcRows.get(srcRows.size() - 1);
  2611. if (srcStartRow == null) {
  2612. throw new IllegalArgumentException("copyRows: First row cannot be null");
  2613. }
  2614. final int srcStartRowNum = srcStartRow.getRowNum();
  2615. final int srcEndRowNum = srcEndRow.getRowNum();
  2616. // check row numbers to make sure they are continuous and increasing (monotonic)
  2617. // and srcRows does not contain null rows
  2618. final int size = srcRows.size();
  2619. for (int index=1; index < size; index++) {
  2620. final Row curRow = srcRows.get(index);
  2621. if (curRow == null) {
  2622. throw new IllegalArgumentException("srcRows may not contain null rows. Found null row at index " + index + ".");
  2623. //} else if (curRow.getRowNum() != prevRow.getRowNum() + 1) {
  2624. // throw new IllegalArgumentException("srcRows must contain continuously increasing row numbers. " +
  2625. // "Got srcRows[" + (index-1) + "]=Row " + prevRow.getRowNum() + ", srcRows[" + index + "]=Row " + curRow.getRowNum() + ".");
  2626. // FIXME: assumes row objects belong to non-null sheets and sheets belong to non-null workbooks.
  2627. } else if (srcStartRow.getSheet().getWorkbook() != curRow.getSheet().getWorkbook()) {
  2628. throw new IllegalArgumentException("All rows in srcRows must belong to the same sheet in the same workbook. " +
  2629. "Expected all rows from same workbook (" + srcStartRow.getSheet().getWorkbook() + "). " +
  2630. "Got srcRows[" + index + "] from different workbook (" + curRow.getSheet().getWorkbook() + ").");
  2631. } else if (srcStartRow.getSheet() != curRow.getSheet()) {
  2632. throw new IllegalArgumentException("All rows in srcRows must belong to the same sheet. " +
  2633. "Expected all rows from " + srcStartRow.getSheet().getSheetName() + ". " +
  2634. "Got srcRows[" + index + "] from " + curRow.getSheet().getSheetName());
  2635. }
  2636. }
  2637. // FIXME: is special behavior needed if srcRows and destRows belong to the same sheets and the regions overlap?
  2638. final CellCopyPolicy options = new CellCopyPolicy(policy);
  2639. // avoid O(N^2) performance scanning through all regions for each row
  2640. // merged regions will be copied after all the rows have been copied
  2641. options.setCopyMergedRegions(false);
  2642. // FIXME: if srcRows contains gaps or null values, clear out those rows that will be overwritten
  2643. // how will this work with merging (copy just values, leave cell styles in place?)
  2644. int r = destStartRow;
  2645. for (Row srcRow : srcRows) {
  2646. int destRowNum;
  2647. if (policy.isCondenseRows()) {
  2648. destRowNum = r++;
  2649. } else {
  2650. final int shift = (srcRow.getRowNum() - srcStartRowNum);
  2651. destRowNum = destStartRow + shift;
  2652. }
  2653. //removeRow(destRowNum); //this probably clears all external formula references to destRow, causing unwanted #REF! errors
  2654. final XSSFRow destRow = createRow(destRowNum);
  2655. destRow.copyRowFrom(srcRow, options);
  2656. }
  2657. // ======================
  2658. // Only do additional copy operations here that cannot be done with Row.copyFromRow(Row, options)
  2659. // reasons: operation needs to interact with multiple rows or sheets
  2660. // Copy merged regions that are contained within the copy region
  2661. if (policy.isCopyMergedRegions()) {
  2662. // FIXME: is this something that rowShifter could be doing?
  2663. final int shift = destStartRow - srcStartRowNum;
  2664. for (CellRangeAddress srcRegion : srcStartRow.getSheet().getMergedRegions()) {
  2665. if (srcStartRowNum <= srcRegion.getFirstRow() && srcRegion.getLastRow() <= srcEndRowNum) {
  2666. // srcRegion is fully inside the copied rows
  2667. final CellRangeAddress destRegion = srcRegion.copy();
  2668. destRegion.setFirstRow(destRegion.getFirstRow() + shift);
  2669. destRegion.setLastRow(destRegion.getLastRow() + shift);
  2670. addMergedRegion(destRegion);
  2671. }
  2672. }
  2673. }
  2674. }
  2675. /**
  2676. * Copies rows between srcStartRow and srcEndRow to the same sheet, starting at destStartRow
  2677. * Convenience function for {@link #copyRows(List, int, CellCopyPolicy)}
  2678. *
  2679. * Equivalent to copyRows(getRows(srcStartRow, srcEndRow, false), destStartRow, cellCopyPolicy)
  2680. *
  2681. * @param srcStartRow the index of the first row to copy the cells from in this sheet
  2682. * @param srcEndRow the index of the last row to copy the cells from in this sheet
  2683. * @param destStartRow the index of the first row to copy the cells to in this sheet
  2684. * @param cellCopyPolicy the policy to use to determine how cells are copied
  2685. */
  2686. @Beta
  2687. public void copyRows(int srcStartRow, int srcEndRow, int destStartRow, CellCopyPolicy cellCopyPolicy) {
  2688. final List<XSSFRow> srcRows = getRows(srcStartRow, srcEndRow, false); //FIXME: should be false, no need to create rows where src is only to copy them to dest
  2689. copyRows(srcRows, destStartRow, cellCopyPolicy);
  2690. }
  2691. /**
  2692. * Shifts rows between startRow and endRow n number of rows.
  2693. * If you use a negative number, it will shift rows up.
  2694. * Code ensures that rows don't wrap around.
  2695. *
  2696. * Calls shiftRows(startRow, endRow, n, false, false);
  2697. *
  2698. * <p>
  2699. * Additionally shifts merged regions that are completely defined in these
  2700. * rows (ie. merged 2 cells on a row to be shifted).
  2701. * @param startRow the row to start shifting
  2702. * @param endRow the row to end shifting
  2703. * @param n the number of rows to shift
  2704. */
  2705. @Override
  2706. public void shiftRows(int startRow, int endRow, int n) {
  2707. shiftRows(startRow, endRow, n, false, false);
  2708. }
  2709. /**
  2710. * Shifts rows between startRow and endRow n number of rows.
  2711. * If you use a negative number, it will shift rows up.
  2712. * Code ensures that rows don't wrap around
  2713. *
  2714. * <p>
  2715. * Additionally shifts merged regions that are completely defined in these
  2716. * rows (ie. merged 2 cells on a row to be shifted). All merged regions that are
  2717. * completely overlaid by shifting will be deleted.
  2718. * <p>
  2719. * @param startRow the row to start shifting
  2720. * @param endRow the row to end shifting
  2721. * @param n the number of rows to shift
  2722. * @param copyRowHeight whether to copy the row height during the shift
  2723. * @param resetOriginalRowHeight whether to set the original row's height to the default
  2724. */
  2725. @Override
  2726. public void shiftRows(int startRow, int endRow, final int n, boolean copyRowHeight, boolean resetOriginalRowHeight) {
  2727. XSSFVMLDrawing vml = getVMLDrawing(false);
  2728. int sheetIndex = getWorkbook().getSheetIndex(this);
  2729. String sheetName = getWorkbook().getSheetName(sheetIndex);
  2730. FormulaShifter formulaShifter = FormulaShifter.createForRowShift(
  2731. sheetIndex, sheetName, startRow, endRow, n, SpreadsheetVersion.EXCEL2007);
  2732. removeOverwritten(vml, startRow, endRow, n);
  2733. shiftCommentsAndRows(vml, startRow, endRow, n);
  2734. XSSFRowShifter rowShifter = new XSSFRowShifter(this);
  2735. rowShifter.shiftMergedRegions(startRow, endRow, n);
  2736. rowShifter.updateNamedRanges(formulaShifter);
  2737. rowShifter.updateFormulas(formulaShifter);
  2738. rowShifter.updateConditionalFormatting(formulaShifter);
  2739. rowShifter.updateHyperlinks(formulaShifter);
  2740. rebuildRows();
  2741. }
  2742. /**
  2743. * Shifts columns between startColumn and endColumn n number of columns.
  2744. * If you use a negative number, it will shift columns left.
  2745. * Code ensures that columns don't wrap around
  2746. *
  2747. * @param startColumn the column to start shifting
  2748. * @param endColumn the column to end shifting
  2749. * @param n length of the shifting step
  2750. */
  2751. @Override
  2752. public void shiftColumns(int startColumn, int endColumn, final int n) {
  2753. XSSFVMLDrawing vml = getVMLDrawing(false);
  2754. shiftCommentsForColumns(vml, startColumn, endColumn, n);
  2755. FormulaShifter formulaShifter = FormulaShifter.createForColumnShift(this.getWorkbook().getSheetIndex(this), this.getSheetName(), startColumn, endColumn, n, SpreadsheetVersion.EXCEL2007);
  2756. XSSFColumnShifter columnShifter = new XSSFColumnShifter(this);
  2757. columnShifter.shiftColumns(startColumn, endColumn, n);
  2758. columnShifter.shiftMergedRegions(startColumn, endColumn, n);
  2759. columnShifter.updateFormulas(formulaShifter);
  2760. columnShifter.updateConditionalFormatting(formulaShifter);
  2761. columnShifter.updateHyperlinks(formulaShifter);
  2762. columnShifter.updateNamedRanges(formulaShifter);
  2763. rebuildRows();
  2764. }
  2765. private void rebuildRows() {
  2766. //rebuild the CTSheetData CTRow order
  2767. SortedMap<Long, CTRow> ctRows = new TreeMap<>();
  2768. CTSheetData sheetData = getCTWorksheet().getSheetData();
  2769. for (CTRow ctRow : sheetData.getRowList()) {
  2770. Long rownumL = ctRow.getR();
  2771. ctRows.put(rownumL, ctRow);
  2772. }
  2773. List<CTRow> ctRowList = new ArrayList<>(ctRows.values());
  2774. CTRow[] ctRowArray = new CTRow[ctRowList.size()];
  2775. ctRowArray = ctRowList.toArray(ctRowArray);
  2776. sheetData.setRowArray(ctRowArray);
  2777. //rebuild the _rows map
  2778. _rows.clear();
  2779. for (CTRow ctRow : sheetData.getRowList()) {
  2780. XSSFRow row = new XSSFRow(ctRow, this);
  2781. Integer rownumI = Math.toIntExact(row.getRowNum());
  2782. _rows.put(rownumI, row);
  2783. }
  2784. }
  2785. // remove all rows which will be overwritten
  2786. private void removeOverwritten(XSSFVMLDrawing vml, int startRow, int endRow, final int n){
  2787. for (Iterator<Row> it = rowIterator() ; it.hasNext() ; ) {
  2788. XSSFRow row = (XSSFRow)it.next();
  2789. int rownum = row.getRowNum();
  2790. // check if we should remove this row as it will be overwritten by the data later
  2791. if (shouldRemoveRow(startRow, endRow, n, rownum)) {
  2792. // remove row from worksheet.getSheetData row array
  2793. // Performance optimization: explicit boxing is slightly faster than auto-unboxing, though may use more memory
  2794. //noinspection UnnecessaryBoxing
  2795. final Integer rownumI = Integer.valueOf(row.getRowNum()); // NOSONAR
  2796. int idx = _rows.headMap(rownumI).size();
  2797. worksheet.getSheetData().removeRow(idx);
  2798. // remove row from _rows
  2799. it.remove();
  2800. // FIXME: (performance optimization) this should be moved outside the for-loop so that comments only needs to be iterated over once.
  2801. // also remove any comments associated with this row
  2802. if(sheetComments != null){
  2803. CTCommentList lst = sheetComments.getCTComments().getCommentList();
  2804. for (CTComment comment : lst.getCommentArray()) {
  2805. String strRef = comment.getRef();
  2806. CellAddress ref = new CellAddress(strRef);
  2807. // is this comment part of the current row?
  2808. if(ref.getRow() == rownum) {
  2809. sheetComments.removeComment(ref);
  2810. vml.removeCommentShape(ref.getRow(), ref.getColumn());
  2811. }
  2812. }
  2813. }
  2814. // FIXME: (performance optimization) this should be moved outside the for-loop so that hyperlinks only needs to be iterated over once.
  2815. // also remove any hyperlinks associated with this row
  2816. if (hyperlinks != null) {
  2817. for (XSSFHyperlink link : new ArrayList<>(hyperlinks)) {
  2818. CellReference ref = new CellReference(link.getCellRef());
  2819. if (ref.getRow() == rownum) {
  2820. hyperlinks.remove(link);
  2821. }
  2822. }
  2823. }
  2824. }
  2825. }
  2826. }
  2827. private void shiftCommentsAndRows(XSSFVMLDrawing vml, int startRow, int endRow, final int n){
  2828. // then do the actual moving and also adjust comments/rowHeight
  2829. // we need to sort it in a way so the shifting does not mess up the structures,
  2830. // i.e. when shifting down, start from down and go up, when shifting up, vice-versa
  2831. SortedMap<XSSFComment, Integer> commentsToShift = new TreeMap<>((o1, o2) -> {
  2832. int row1 = o1.getRow();
  2833. int row2 = o2.getRow();
  2834. if (row1 == row2) {
  2835. // ordering is not important when row is equal, but don't return zero to still
  2836. // get multiple comments per row into the map
  2837. return o1.hashCode() - o2.hashCode();
  2838. }
  2839. // when shifting down, sort higher row-values first
  2840. if (n > 0) {
  2841. return row1 < row2 ? 1 : -1;
  2842. } else {
  2843. // sort lower-row values first when shifting up
  2844. return row1 > row2 ? 1 : -1;
  2845. }
  2846. });
  2847. for (Iterator<Row> it = rowIterator() ; it.hasNext() ; ) {
  2848. XSSFRow row = (XSSFRow)it.next();
  2849. int rownum = row.getRowNum();
  2850. if(sheetComments != null){
  2851. // calculate the new rownum
  2852. int newrownum = shiftedRowNum(startRow, endRow, n, rownum);
  2853. // is there a change necessary for the current row?
  2854. if(newrownum != rownum) {
  2855. CTCommentList lst = sheetComments.getCTComments().getCommentList();
  2856. for (CTComment comment : lst.getCommentArray()) {
  2857. String oldRef = comment.getRef();
  2858. CellReference ref = new CellReference(oldRef);
  2859. // is this comment part of the current row?
  2860. if(ref.getRow() == rownum) {
  2861. XSSFComment xssfComment = new XSSFComment(sheetComments, comment,
  2862. vml == null ? null : vml.findCommentShape(rownum, ref.getCol()));
  2863. // we should not perform the shifting right here as we would then find
  2864. // already shifted comments and would shift them again...
  2865. commentsToShift.put(xssfComment, newrownum);
  2866. }
  2867. }
  2868. }
  2869. }
  2870. if(rownum < startRow || rownum > endRow) {
  2871. continue;
  2872. }
  2873. row.shift(n);
  2874. }
  2875. // adjust all the affected comment-structures now
  2876. // the Map is sorted and thus provides them in the order that we need here,
  2877. // i.e. from down to up if shifting down, vice-versa otherwise
  2878. for(Map.Entry<XSSFComment, Integer> entry : commentsToShift.entrySet()) {
  2879. entry.getKey().setRow(entry.getValue());
  2880. }
  2881. rebuildRows();
  2882. }
  2883. private int shiftedRowNum(int startRow, int endRow, int n, int rownum) {
  2884. // no change if before any affected row
  2885. if(rownum < startRow && (n > 0 || (startRow - rownum) > n)) {
  2886. return rownum;
  2887. }
  2888. // no change if after any affected row
  2889. if(rownum > endRow && (n < 0 || (rownum - endRow) > n)) {
  2890. return rownum;
  2891. }
  2892. // row before and things are moved up
  2893. if(rownum < startRow) {
  2894. // row is moved down by the shifting
  2895. return rownum + (endRow - startRow);
  2896. }
  2897. // row is after and things are moved down
  2898. if(rownum > endRow) {
  2899. // row is moved up by the shifting
  2900. return rownum - (endRow - startRow);
  2901. }
  2902. // row is part of the shifted block
  2903. return rownum + n;
  2904. }
  2905. private void shiftCommentsForColumns(XSSFVMLDrawing vml, int startColumnIndex, int endColumnIndex, final int n){
  2906. // then do the actual moving and also adjust comments/rowHeight
  2907. // we need to sort it in a way so the shifting does not mess up the structures,
  2908. // i.e. when shifting down, start from down and go up, when shifting up, vice-versa
  2909. SortedMap<XSSFComment, Integer> commentsToShift = new TreeMap<>((o1, o2) -> {
  2910. int column1 = o1.getColumn();
  2911. int column2 = o2.getColumn();
  2912. if (column1 == column2) {
  2913. // ordering is not important when row is equal, but don't return zero to still
  2914. // get multiple comments per row into the map
  2915. return o1.hashCode() - o2.hashCode();
  2916. }
  2917. // when shifting down, sort higher row-values first
  2918. if (n > 0) {
  2919. return column1 < column2 ? 1 : -1;
  2920. } else {
  2921. // sort lower-row values first when shifting up
  2922. return column1 > column2 ? 1 : -1;
  2923. }
  2924. });
  2925. if(sheetComments != null){
  2926. CTCommentList lst = sheetComments.getCTComments().getCommentList();
  2927. for (CTComment comment : lst.getCommentArray()) {
  2928. String oldRef = comment.getRef();
  2929. CellReference ref = new CellReference(oldRef);
  2930. int columnIndex =ref.getCol();
  2931. int newColumnIndex = shiftedRowNum(startColumnIndex, endColumnIndex, n, columnIndex);
  2932. if(newColumnIndex != columnIndex){
  2933. XSSFComment xssfComment = new XSSFComment(sheetComments, comment,
  2934. vml == null ? null : vml.findCommentShape(ref.getRow(), columnIndex));
  2935. commentsToShift.put(xssfComment, newColumnIndex);
  2936. }
  2937. }
  2938. }
  2939. // adjust all the affected comment-structures now
  2940. // the Map is sorted and thus provides them in the order that we need here,
  2941. // i.e. from down to up if shifting down, vice-versa otherwise
  2942. for(Map.Entry<XSSFComment, Integer> entry : commentsToShift.entrySet()) {
  2943. entry.getKey().setColumn(entry.getValue());
  2944. }
  2945. rebuildRows();
  2946. }
  2947. /**
  2948. * Location of the top left visible cell Location of the top left visible cell in the bottom right
  2949. * pane (when in Left-to-Right mode).
  2950. *
  2951. * @param topRow the top row to show in desktop window pane
  2952. * @param leftCol the left column to show in desktop window pane
  2953. */
  2954. @Override
  2955. public void showInPane(int topRow, int leftCol) {
  2956. final CellReference cellReference = new CellReference(topRow, leftCol);
  2957. final String cellRef = cellReference.formatAsString();
  2958. final CTPane pane = getPane(true);
  2959. assert(pane != null);
  2960. pane.setTopLeftCell(cellRef);
  2961. }
  2962. @Override
  2963. public void ungroupColumn(int fromColumn, int toColumn) {
  2964. CTCols cols = worksheet.getColsArray(0);
  2965. for (int index = fromColumn; index <= toColumn; index++) {
  2966. CTCol col = columnHelper.getColumn(index, false);
  2967. if (col != null) {
  2968. short outlineLevel = col.getOutlineLevel();
  2969. col.setOutlineLevel((short) (outlineLevel - 1));
  2970. index = Math.toIntExact(col.getMax());
  2971. if (col.getOutlineLevel() <= 0) {
  2972. int colIndex = columnHelper.getIndexOfColumn(cols, col);
  2973. worksheet.getColsArray(0).removeCol(colIndex);
  2974. }
  2975. }
  2976. }
  2977. worksheet.setColsArray(0, cols);
  2978. setSheetFormatPrOutlineLevelCol();
  2979. }
  2980. /**
  2981. * Ungroup a range of rows that were previously groupped
  2982. *
  2983. * @param fromRow start row (0-based)
  2984. * @param toRow end row (0-based)
  2985. */
  2986. @Override
  2987. public void ungroupRow(int fromRow, int toRow) {
  2988. for (int i = fromRow; i <= toRow; i++) {
  2989. XSSFRow xrow = getRow(i);
  2990. if (xrow != null) {
  2991. CTRow ctRow = xrow.getCTRow();
  2992. int outlineLevel = ctRow.getOutlineLevel();
  2993. ctRow.setOutlineLevel((short) (outlineLevel - 1));
  2994. //remove a row only if the row has no cell and if the outline level is 0
  2995. if (outlineLevel == 1 && xrow.getFirstCellNum() == -1) {
  2996. removeRow(xrow);
  2997. }
  2998. }
  2999. }
  3000. setSheetFormatPrOutlineLevelRow();
  3001. }
  3002. private void setSheetFormatPrOutlineLevelRow(){
  3003. short maxLevelRow=getMaxOutlineLevelRows();
  3004. getSheetTypeSheetFormatPr().setOutlineLevelRow(maxLevelRow);
  3005. }
  3006. private void setSheetFormatPrOutlineLevelCol(){
  3007. short maxLevelCol=getMaxOutlineLevelCols();
  3008. getSheetTypeSheetFormatPr().setOutlineLevelCol(maxLevelCol);
  3009. }
  3010. protected CTSheetViews getSheetTypeSheetViews(final boolean create) {
  3011. final CTSheetViews views = (worksheet.isSetSheetViews() || !create)
  3012. ? worksheet.getSheetViews() : worksheet.addNewSheetViews();
  3013. assert(views != null || !create);
  3014. if (views == null) {
  3015. return null;
  3016. }
  3017. if (views.sizeOfSheetViewArray() == 0 && create) {
  3018. views.addNewSheetView();
  3019. }
  3020. return views;
  3021. }
  3022. /**
  3023. * Returns a flag indicating whether this sheet is selected.
  3024. * <p>
  3025. * When only 1 sheet is selected and active, this value should be in synch with the activeTab value.
  3026. * In case of a conflict, the Start Part setting wins and sets the active sheet tab.
  3027. * </p>
  3028. * Note: multiple sheets can be selected, but only one sheet can be active at one time.
  3029. *
  3030. * @return <code>true</code> if this sheet is selected
  3031. */
  3032. @Override
  3033. public boolean isSelected() {
  3034. final CTSheetView dsv = getDefaultSheetView(false);
  3035. return dsv != null && dsv.getTabSelected();
  3036. }
  3037. /**
  3038. * Sets a flag indicating whether this sheet is selected.
  3039. *
  3040. * <p>
  3041. * When only 1 sheet is selected and active, this value should be in synch with the activeTab value.
  3042. * In case of a conflict, the Start Part setting wins and sets the active sheet tab.
  3043. * </p>
  3044. * Note: multiple sheets can be selected, but only one sheet can be active at one time.
  3045. *
  3046. * @param value <code>true</code> if this sheet is selected
  3047. */
  3048. @Override
  3049. public void setSelected(boolean value) {
  3050. final CTSheetViews views = getSheetTypeSheetViews(true);
  3051. assert(views != null);
  3052. for (CTSheetView view : views.getSheetViewArray()) {
  3053. view.setTabSelected(value);
  3054. }
  3055. }
  3056. /**
  3057. * Register a hyperlink in the collection of hyperlinks on this sheet
  3058. *
  3059. * @param hyperlink the link to add
  3060. */
  3061. @Internal
  3062. public void addHyperlink(XSSFHyperlink hyperlink) {
  3063. hyperlinks.add(hyperlink);
  3064. }
  3065. /**
  3066. * Removes a hyperlink in the collection of hyperlinks on this sheet
  3067. *
  3068. * @param row row index
  3069. * @param column column index
  3070. */
  3071. @Internal
  3072. public void removeHyperlink(int row, int column) {
  3073. // CTHyperlinks is regenerated from scratch when writing out the spreadsheet
  3074. // so don't worry about maintaining hyperlinks and CTHyperlinks in parallel.
  3075. // only maintain hyperlinks
  3076. String ref = new CellReference(row, column).formatAsString();
  3077. for (Iterator<XSSFHyperlink> it = hyperlinks.iterator(); it.hasNext();) {
  3078. XSSFHyperlink hyperlink = it.next();
  3079. if (hyperlink.getCellRef().equals(ref)) {
  3080. it.remove();
  3081. return;
  3082. }
  3083. }
  3084. }
  3085. /**
  3086. * Return location of the active cell, e.g. <code>A1</code>.
  3087. *
  3088. * @return the location of the active cell.
  3089. */
  3090. @Override
  3091. public CellAddress getActiveCell() {
  3092. final CTSelection sts = getSheetTypeSelection(false);
  3093. final String address = (sts != null) ? sts.getActiveCell() : null;
  3094. return (address != null) ? new CellAddress(address) : null;
  3095. }
  3096. /**
  3097. * {@inheritDoc}
  3098. */
  3099. @Override
  3100. public void setActiveCell(CellAddress address) {
  3101. final CTSelection ctsel = getSheetTypeSelection(true);
  3102. assert(ctsel != null);
  3103. String ref = address.formatAsString();
  3104. ctsel.setActiveCell(ref);
  3105. ctsel.setSqref(Collections.singletonList(ref));
  3106. }
  3107. /**
  3108. * Does this sheet have any comments on it? We need to know,
  3109. * so we can decide about writing it to disk or not
  3110. */
  3111. public boolean hasComments() {
  3112. return sheetComments != null && sheetComments.getNumberOfComments() > 0;
  3113. }
  3114. protected int getNumberOfComments() {
  3115. return sheetComments == null ? 0 : sheetComments.getNumberOfComments();
  3116. }
  3117. private CTSelection getSheetTypeSelection(final boolean create) {
  3118. final CTSheetView dsv = getDefaultSheetView(create);
  3119. assert(dsv != null || !create);
  3120. if (dsv == null) {
  3121. return null;
  3122. }
  3123. final int sz = dsv.sizeOfSelectionArray();
  3124. if (sz == 0) {
  3125. return create ? dsv.addNewSelection() : null;
  3126. }
  3127. return dsv.getSelectionArray(sz - 1);
  3128. }
  3129. /**
  3130. * Return the default sheet view. This is the last one if the sheet's views, according to sec. 3.3.1.83
  3131. * of the OOXML spec: "A single sheet view definition. When more than 1 sheet view is defined in the file,
  3132. * it means that when opening the workbook, each sheet view corresponds to a separate window within the
  3133. * spreadsheet application, where each window is showing the particular sheet. containing the same
  3134. * workbookViewId value, the last sheetView definition is loaded, and the others are discarded.
  3135. * When multiple windows are viewing the same sheet, multiple sheetView elements (with corresponding
  3136. * workbookView entries) are saved."
  3137. */
  3138. private CTSheetView getDefaultSheetView(final boolean create) {
  3139. final CTSheetViews views = getSheetTypeSheetViews(create);
  3140. assert(views != null || !create);
  3141. if (views == null) {
  3142. return null;
  3143. }
  3144. final int sz = views.sizeOfSheetViewArray();
  3145. assert(sz > 0 || !create);
  3146. return (sz == 0) ? null : views.getSheetViewArray(sz - 1);
  3147. }
  3148. /**
  3149. * Returns the sheet's comments object if there is one,
  3150. * or null if not
  3151. *
  3152. * @param create create a new comments table if it does not exist
  3153. */
  3154. protected CommentsTable getCommentsTable(boolean create) {
  3155. if(sheetComments == null && create){
  3156. // Try to create a comments table with the same number as
  3157. // the sheet has (i.e. sheet 1 -> comments 1)
  3158. try {
  3159. sheetComments = (CommentsTable)createRelationship(
  3160. XSSFRelation.SHEET_COMMENTS, XSSFFactory.getInstance(), Math.toIntExact(sheet.getSheetId()));
  3161. } catch(PartAlreadyExistsException e) {
  3162. // Technically a sheet doesn't need the same number as
  3163. // it's comments, and clearly someone has already pinched
  3164. // our number! Go for the next available one instead
  3165. sheetComments = (CommentsTable)createRelationship(
  3166. XSSFRelation.SHEET_COMMENTS, XSSFFactory.getInstance(), -1);
  3167. }
  3168. }
  3169. return sheetComments;
  3170. }
  3171. private CTPageSetUpPr getSheetTypePageSetUpPr() {
  3172. CTSheetPr sheetPr = getSheetTypeSheetPr();
  3173. return sheetPr.isSetPageSetUpPr() ? sheetPr.getPageSetUpPr() : sheetPr.addNewPageSetUpPr();
  3174. }
  3175. private static boolean shouldRemoveRow(int startRow, int endRow, int n, int rownum) {
  3176. // is this row in the target-window where the moved rows will land?
  3177. if (rownum >= (startRow + n) && rownum <= (endRow + n)) {
  3178. // only remove it if the current row is not part of the data that is copied
  3179. if (n > 0 && rownum > endRow) {
  3180. return true;
  3181. }
  3182. else {
  3183. return n < 0 && rownum < startRow;
  3184. }
  3185. }
  3186. return false;
  3187. }
  3188. private CTPane getPane(final boolean create) {
  3189. final CTSheetView dsv = getDefaultSheetView(create);
  3190. assert(dsv != null || !create);
  3191. if (dsv == null) {
  3192. return null;
  3193. }
  3194. return (dsv.isSetPane() || !create) ? dsv.getPane() : dsv.addNewPane();
  3195. }
  3196. /**
  3197. * Return a master shared formula by index
  3198. *
  3199. * @param sid shared group index
  3200. * @return a CTCellFormula bean holding shared formula or <code>null</code> if not found
  3201. */
  3202. @Internal
  3203. public CTCellFormula getSharedFormula(int sid){
  3204. return sharedFormulas.get(sid);
  3205. }
  3206. void onReadCell(XSSFCell cell){
  3207. //collect cells holding shared formulas
  3208. CTCell ct = cell.getCTCell();
  3209. CTCellFormula f = ct.getF();
  3210. if (f != null && f.getT() == STCellFormulaType.SHARED && f.isSetRef() && f.getStringValue() != null) {
  3211. // save a detached copy to avoid XmlValueDisconnectedException,
  3212. // this may happen when the master cell of a shared formula is changed
  3213. CTCellFormula sf = (CTCellFormula)f.copy();
  3214. CellRangeAddress sfRef = CellRangeAddress.valueOf(sf.getRef());
  3215. CellReference cellRef = new CellReference(cell);
  3216. // If the shared formula range precedes the master cell then the preceding part is discarded, e.g.
  3217. // if the cell is E60 and the shared formula range is C60:M85 then the effective range is E60:M85
  3218. // see more details in https://issues.apache.org/bugzilla/show_bug.cgi?id=51710
  3219. if(cellRef.getCol() > sfRef.getFirstColumn() || cellRef.getRow() > sfRef.getFirstRow()){
  3220. String effectiveRef = new CellRangeAddress(
  3221. Math.max(cellRef.getRow(), sfRef.getFirstRow()), Math.max(cellRef.getRow(), sfRef.getLastRow()),
  3222. Math.max(cellRef.getCol(), sfRef.getFirstColumn()), Math.max(cellRef.getCol(), sfRef.getLastColumn()))
  3223. .formatAsString();
  3224. sf.setRef(effectiveRef);
  3225. }
  3226. sharedFormulas.put(Math.toIntExact(f.getSi()), sf);
  3227. }
  3228. if (f != null && f.getT() == STCellFormulaType.ARRAY && f.getRef() != null) {
  3229. arrayFormulas.add(CellRangeAddress.valueOf(f.getRef()));
  3230. }
  3231. }
  3232. @Override
  3233. protected void commit() throws IOException {
  3234. PackagePart part = getPackagePart();
  3235. OutputStream out = part.getOutputStream();
  3236. write(out);
  3237. out.close();
  3238. }
  3239. protected void write(OutputStream out) throws IOException {
  3240. boolean setToNull = false;
  3241. if(worksheet.sizeOfColsArray() == 1) {
  3242. CTCols col = worksheet.getColsArray(0);
  3243. if(col.sizeOfColArray() == 0) {
  3244. setToNull = true;
  3245. // this is necessary so that we do not write an empty <cols/> item into the sheet-xml in the xlsx-file
  3246. // Excel complains about a corrupted file if this shows up there!
  3247. worksheet.setColsArray(null);
  3248. } else {
  3249. setColWidthAttribute(col);
  3250. }
  3251. }
  3252. // Now re-generate our CTHyperlinks, if needed
  3253. if(hyperlinks.size() > 0) {
  3254. if(worksheet.getHyperlinks() == null) {
  3255. worksheet.addNewHyperlinks();
  3256. }
  3257. CTHyperlink[] ctHls = new CTHyperlink[hyperlinks.size()];
  3258. for(int i=0; i<ctHls.length; i++) {
  3259. // If our sheet has hyperlinks, have them add
  3260. // any relationships that they might need
  3261. XSSFHyperlink hyperlink = hyperlinks.get(i);
  3262. hyperlink.generateRelationIfNeeded(getPackagePart());
  3263. // Now grab their underling object
  3264. ctHls[i] = hyperlink.getCTHyperlink();
  3265. }
  3266. worksheet.getHyperlinks().setHyperlinkArray(ctHls);
  3267. }
  3268. else {
  3269. if (worksheet.getHyperlinks() != null) {
  3270. final int count = worksheet.getHyperlinks().sizeOfHyperlinkArray();
  3271. for (int i=count-1; i>=0; i--) {
  3272. worksheet.getHyperlinks().removeHyperlink(i);
  3273. }
  3274. // For some reason, we have to remove the hyperlinks one by one from the CTHyperlinks array
  3275. // before unsetting the hyperlink array.
  3276. // Resetting the hyperlink array seems to break some XML nodes.
  3277. //worksheet.getHyperlinks().setHyperlinkArray(new CTHyperlink[0]);
  3278. worksheet.unsetHyperlinks();
  3279. } /*else {
  3280. // nothing to do
  3281. }*/
  3282. }
  3283. int minCell = Integer.MAX_VALUE, maxCell = Integer.MIN_VALUE;
  3284. for(Map.Entry<Integer, XSSFRow> entry : _rows.entrySet()) {
  3285. XSSFRow row = entry.getValue();
  3286. // first perform the normal write actions for the row
  3287. row.onDocumentWrite();
  3288. // then calculate min/max cell-numbers for the worksheet-dimension
  3289. if(row.getFirstCellNum() != -1) {
  3290. minCell = Math.min(minCell, row.getFirstCellNum());
  3291. }
  3292. if(row.getLastCellNum() != -1) {
  3293. maxCell = Math.max(maxCell, row.getLastCellNum()-1);
  3294. }
  3295. }
  3296. // finally, if we had at least one cell we can populate the optional dimension-field
  3297. if(minCell != Integer.MAX_VALUE) {
  3298. String ref = new CellRangeAddress(getFirstRowNum(), getLastRowNum(), minCell, maxCell).formatAsString();
  3299. if(worksheet.isSetDimension()) {
  3300. worksheet.getDimension().setRef(ref);
  3301. } else {
  3302. worksheet.addNewDimension().setRef(ref);
  3303. }
  3304. }
  3305. XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
  3306. xmlOptions.setSaveSyntheticDocumentElement(new QName(CTWorksheet.type.getName().getNamespaceURI(), "worksheet"));
  3307. worksheet.save(out, xmlOptions);
  3308. // Bug 52233: Ensure that we have a col-array even if write() removed it
  3309. if(setToNull) {
  3310. worksheet.addNewCols();
  3311. }
  3312. }
  3313. /**
  3314. * @return true when Autofilters are locked and the sheet is protected.
  3315. */
  3316. public boolean isAutoFilterLocked() {
  3317. return isSheetLocked() && safeGetProtectionField().getAutoFilter();
  3318. }
  3319. /**
  3320. * @return true when Deleting columns is locked and the sheet is protected.
  3321. */
  3322. public boolean isDeleteColumnsLocked() {
  3323. return isSheetLocked() && safeGetProtectionField().getDeleteColumns();
  3324. }
  3325. /**
  3326. * @return true when Deleting rows is locked and the sheet is protected.
  3327. */
  3328. public boolean isDeleteRowsLocked() {
  3329. return isSheetLocked() && safeGetProtectionField().getDeleteRows();
  3330. }
  3331. /**
  3332. * @return true when Formatting cells is locked and the sheet is protected.
  3333. */
  3334. public boolean isFormatCellsLocked() {
  3335. return isSheetLocked() && safeGetProtectionField().getFormatCells();
  3336. }
  3337. /**
  3338. * @return true when Formatting columns is locked and the sheet is protected.
  3339. */
  3340. public boolean isFormatColumnsLocked() {
  3341. return isSheetLocked() && safeGetProtectionField().getFormatColumns();
  3342. }
  3343. /**
  3344. * @return true when Formatting rows is locked and the sheet is protected.
  3345. */
  3346. public boolean isFormatRowsLocked() {
  3347. return isSheetLocked() && safeGetProtectionField().getFormatRows();
  3348. }
  3349. /**
  3350. * @return true when Inserting columns is locked and the sheet is protected.
  3351. */
  3352. public boolean isInsertColumnsLocked() {
  3353. return isSheetLocked() && safeGetProtectionField().getInsertColumns();
  3354. }
  3355. /**
  3356. * @return true when Inserting hyperlinks is locked and the sheet is protected.
  3357. */
  3358. public boolean isInsertHyperlinksLocked() {
  3359. return isSheetLocked() && safeGetProtectionField().getInsertHyperlinks();
  3360. }
  3361. /**
  3362. * @return true when Inserting rows is locked and the sheet is protected.
  3363. */
  3364. public boolean isInsertRowsLocked() {
  3365. return isSheetLocked() && safeGetProtectionField().getInsertRows();
  3366. }
  3367. /**
  3368. * @return true when Pivot tables are locked and the sheet is protected.
  3369. */
  3370. public boolean isPivotTablesLocked() {
  3371. return isSheetLocked() && safeGetProtectionField().getPivotTables();
  3372. }
  3373. /**
  3374. * @return true when Sorting is locked and the sheet is protected.
  3375. */
  3376. public boolean isSortLocked() {
  3377. return isSheetLocked() && safeGetProtectionField().getSort();
  3378. }
  3379. /**
  3380. * @return true when Objects are locked and the sheet is protected.
  3381. */
  3382. public boolean isObjectsLocked() {
  3383. return isSheetLocked() && safeGetProtectionField().getObjects();
  3384. }
  3385. /**
  3386. * @return true when Scenarios are locked and the sheet is protected.
  3387. */
  3388. public boolean isScenariosLocked() {
  3389. return isSheetLocked() && safeGetProtectionField().getScenarios();
  3390. }
  3391. /**
  3392. * @return true when Selection of locked cells is locked and the sheet is protected.
  3393. */
  3394. public boolean isSelectLockedCellsLocked() {
  3395. return isSheetLocked() && safeGetProtectionField().getSelectLockedCells();
  3396. }
  3397. /**
  3398. * @return true when Selection of unlocked cells is locked and the sheet is protected.
  3399. */
  3400. public boolean isSelectUnlockedCellsLocked() {
  3401. return isSheetLocked() && safeGetProtectionField().getSelectUnlockedCells();
  3402. }
  3403. /**
  3404. * @return true when Sheet is Protected.
  3405. */
  3406. public boolean isSheetLocked() {
  3407. return worksheet.isSetSheetProtection() && safeGetProtectionField().getSheet();
  3408. }
  3409. /**
  3410. * Enable sheet protection
  3411. */
  3412. public void enableLocking() {
  3413. safeGetProtectionField().setSheet(true);
  3414. }
  3415. /**
  3416. * Disable sheet protection
  3417. */
  3418. public void disableLocking() {
  3419. safeGetProtectionField().setSheet(false);
  3420. }
  3421. /**
  3422. * Enable or disable Autofilters locking.
  3423. * This does not modify sheet protection status.
  3424. * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()}
  3425. */
  3426. public void lockAutoFilter(boolean enabled) {
  3427. safeGetProtectionField().setAutoFilter(enabled);
  3428. }
  3429. /**
  3430. * Enable or disable Deleting columns locking.
  3431. * This does not modify sheet protection status.
  3432. * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()}
  3433. */
  3434. public void lockDeleteColumns(boolean enabled) {
  3435. safeGetProtectionField().setDeleteColumns(enabled);
  3436. }
  3437. /**
  3438. * Enable or disable Deleting rows locking.
  3439. * This does not modify sheet protection status.
  3440. * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()}
  3441. */
  3442. public void lockDeleteRows(boolean enabled) {
  3443. safeGetProtectionField().setDeleteRows(enabled);
  3444. }
  3445. /**
  3446. * Enable or disable Formatting cells locking.
  3447. * This does not modify sheet protection status.
  3448. * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()}
  3449. */
  3450. public void lockFormatCells(boolean enabled) {
  3451. safeGetProtectionField().setFormatCells(enabled);
  3452. }
  3453. /**
  3454. * Enable or disable Formatting columns locking.
  3455. * This does not modify sheet protection status.
  3456. * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()}
  3457. */
  3458. public void lockFormatColumns(boolean enabled) {
  3459. safeGetProtectionField().setFormatColumns(enabled);
  3460. }
  3461. /**
  3462. * Enable or disable Formatting rows locking.
  3463. * This does not modify sheet protection status.
  3464. * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()}
  3465. */
  3466. public void lockFormatRows(boolean enabled) {
  3467. safeGetProtectionField().setFormatRows(enabled);
  3468. }
  3469. /**
  3470. * Enable or disable Inserting columns locking.
  3471. * This does not modify sheet protection status.
  3472. * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()}
  3473. */
  3474. public void lockInsertColumns(boolean enabled) {
  3475. safeGetProtectionField().setInsertColumns(enabled);
  3476. }
  3477. /**
  3478. * Enable or disable Inserting hyperlinks locking.
  3479. * This does not modify sheet protection status.
  3480. * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()}
  3481. */
  3482. public void lockInsertHyperlinks(boolean enabled) {
  3483. safeGetProtectionField().setInsertHyperlinks(enabled);
  3484. }
  3485. /**
  3486. * Enable or disable Inserting rows locking.
  3487. * This does not modify sheet protection status.
  3488. * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()}
  3489. */
  3490. public void lockInsertRows(boolean enabled) {
  3491. safeGetProtectionField().setInsertRows(enabled);
  3492. }
  3493. /**
  3494. * Enable or disable Pivot Tables locking.
  3495. * This does not modify sheet protection status.
  3496. * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()}
  3497. */
  3498. public void lockPivotTables(boolean enabled) {
  3499. safeGetProtectionField().setPivotTables(enabled);
  3500. }
  3501. /**
  3502. * Enable or disable Sort locking.
  3503. * This does not modify sheet protection status.
  3504. * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()}
  3505. */
  3506. public void lockSort(boolean enabled) {
  3507. safeGetProtectionField().setSort(enabled);
  3508. }
  3509. /**
  3510. * Enable or disable Objects locking.
  3511. * This does not modify sheet protection status.
  3512. * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()}
  3513. */
  3514. public void lockObjects(boolean enabled) {
  3515. safeGetProtectionField().setObjects(enabled);
  3516. }
  3517. /**
  3518. * Enable or disable Scenarios locking.
  3519. * This does not modify sheet protection status.
  3520. * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()}
  3521. */
  3522. public void lockScenarios(boolean enabled) {
  3523. safeGetProtectionField().setScenarios(enabled);
  3524. }
  3525. /**
  3526. * Enable or disable Selection of locked cells locking.
  3527. * This does not modify sheet protection status.
  3528. * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()}
  3529. */
  3530. public void lockSelectLockedCells(boolean enabled) {
  3531. safeGetProtectionField().setSelectLockedCells(enabled);
  3532. }
  3533. /**
  3534. * Enable or disable Selection of unlocked cells locking.
  3535. * This does not modify sheet protection status.
  3536. * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()}
  3537. */
  3538. public void lockSelectUnlockedCells(boolean enabled) {
  3539. safeGetProtectionField().setSelectUnlockedCells(enabled);
  3540. }
  3541. private CTSheetProtection safeGetProtectionField() {
  3542. if (!isSheetProtectionEnabled()) {
  3543. return worksheet.addNewSheetProtection();
  3544. }
  3545. return worksheet.getSheetProtection();
  3546. }
  3547. /* package */ boolean isSheetProtectionEnabled() {
  3548. return (worksheet.isSetSheetProtection());
  3549. }
  3550. /* package */ boolean isCellInArrayFormulaContext(XSSFCell cell) {
  3551. for (CellRangeAddress range : arrayFormulas) {
  3552. if (range.isInRange(cell.getRowIndex(), cell.getColumnIndex())) {
  3553. return true;
  3554. }
  3555. }
  3556. return false;
  3557. }
  3558. /* package */ XSSFCell getFirstCellInArrayFormula(XSSFCell cell) {
  3559. for (CellRangeAddress range : arrayFormulas) {
  3560. if (range.isInRange(cell.getRowIndex(), cell.getColumnIndex())) {
  3561. return getRow(range.getFirstRow()).getCell(range.getFirstColumn());
  3562. }
  3563. }
  3564. return null;
  3565. }
  3566. /**
  3567. * Also creates cells if they don't exist
  3568. */
  3569. private CellRange<XSSFCell> getCellRange(CellRangeAddress range) {
  3570. int firstRow = range.getFirstRow();
  3571. int firstColumn = range.getFirstColumn();
  3572. int lastRow = range.getLastRow();
  3573. int lastColumn = range.getLastColumn();
  3574. int height = lastRow - firstRow + 1;
  3575. int width = lastColumn - firstColumn + 1;
  3576. List<XSSFCell> temp = new ArrayList<>(height * width);
  3577. for (int rowIn = firstRow; rowIn <= lastRow; rowIn++) {
  3578. for (int colIn = firstColumn; colIn <= lastColumn; colIn++) {
  3579. XSSFRow row = getRow(rowIn);
  3580. if (row == null) {
  3581. row = createRow(rowIn);
  3582. }
  3583. XSSFCell cell = row.getCell(colIn);
  3584. if (cell == null) {
  3585. cell = row.createCell(colIn);
  3586. }
  3587. temp.add(cell);
  3588. }
  3589. }
  3590. return SSCellRange.create(firstRow, firstColumn, height, width, temp, XSSFCell.class);
  3591. }
  3592. @Override
  3593. public CellRange<XSSFCell> setArrayFormula(String formula, CellRangeAddress range) {
  3594. CellRange<XSSFCell> cr = getCellRange(range);
  3595. XSSFCell mainArrayFormulaCell = cr.getTopLeftCell();
  3596. mainArrayFormulaCell.setCellArrayFormula(formula, range);
  3597. arrayFormulas.add(range);
  3598. return cr;
  3599. }
  3600. @Override
  3601. public CellRange<XSSFCell> removeArrayFormula(Cell cell) {
  3602. if (cell.getSheet() != this) {
  3603. throw new IllegalArgumentException("Specified cell does not belong to this sheet.");
  3604. }
  3605. for (CellRangeAddress range : arrayFormulas) {
  3606. if (range.isInRange(cell)) {
  3607. arrayFormulas.remove(range);
  3608. CellRange<XSSFCell> cr = getCellRange(range);
  3609. for (XSSFCell c : cr) {
  3610. c.setBlank();
  3611. }
  3612. return cr;
  3613. }
  3614. }
  3615. String ref = new CellReference(cell).formatAsString();
  3616. throw new IllegalArgumentException("Cell " + ref + " is not part of an array formula.");
  3617. }
  3618. @Override
  3619. public DataValidationHelper getDataValidationHelper() {
  3620. return dataValidationHelper;
  3621. }
  3622. @Override
  3623. public List<XSSFDataValidation> getDataValidations() {
  3624. List<XSSFDataValidation> xssfValidations = new ArrayList<>();
  3625. CTDataValidations dataValidations = this.worksheet.getDataValidations();
  3626. if (dataValidations != null) {
  3627. for (CTDataValidation ctDataValidation : dataValidations.getDataValidationArray()) {
  3628. CellRangeAddressList addressList = new CellRangeAddressList();
  3629. @SuppressWarnings("unchecked")
  3630. List<String> sqref = ctDataValidation.getSqref();
  3631. for (String stRef : sqref) {
  3632. String[] regions = stRef.split(" ");
  3633. for (String region : regions) {
  3634. String[] parts = region.split(":");
  3635. CellReference begin = new CellReference(parts[0]);
  3636. CellReference end = parts.length > 1 ? new CellReference(parts[1]) : begin;
  3637. CellRangeAddress cellRangeAddress = new CellRangeAddress(begin.getRow(), end.getRow(), begin.getCol(), end.getCol());
  3638. addressList.addCellRangeAddress(cellRangeAddress);
  3639. }
  3640. }
  3641. XSSFDataValidation xssfDataValidation = new XSSFDataValidation(addressList, ctDataValidation);
  3642. xssfValidations.add(xssfDataValidation);
  3643. }
  3644. }
  3645. return xssfValidations;
  3646. }
  3647. @Override
  3648. public void addValidationData(DataValidation dataValidation) {
  3649. XSSFDataValidation xssfDataValidation = (XSSFDataValidation)dataValidation;
  3650. CTDataValidations dataValidations = worksheet.getDataValidations();
  3651. if( dataValidations==null ) {
  3652. dataValidations = worksheet.addNewDataValidations();
  3653. }
  3654. int currentCount = dataValidations.sizeOfDataValidationArray();
  3655. CTDataValidation newval = dataValidations.addNewDataValidation();
  3656. newval.set(xssfDataValidation.getCtDataValidation());
  3657. dataValidations.setCount(currentCount + 1L);
  3658. }
  3659. @Override
  3660. public XSSFAutoFilter setAutoFilter(CellRangeAddress range) {
  3661. CTAutoFilter af = worksheet.getAutoFilter();
  3662. if(af == null) {
  3663. af = worksheet.addNewAutoFilter();
  3664. }
  3665. CellRangeAddress norm = new CellRangeAddress(range.getFirstRow(), range.getLastRow(),
  3666. range.getFirstColumn(), range.getLastColumn());
  3667. String ref = norm.formatAsString();
  3668. af.setRef(ref);
  3669. XSSFWorkbook wb = getWorkbook();
  3670. int sheetIndex = getWorkbook().getSheetIndex(this);
  3671. XSSFName name = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, sheetIndex);
  3672. if (name == null) {
  3673. name = wb.createBuiltInName(XSSFName.BUILTIN_FILTER_DB, sheetIndex);
  3674. }
  3675. name.getCTName().setHidden(true);
  3676. CellReference r1 = new CellReference(getSheetName(), range.getFirstRow(), range.getFirstColumn(), true, true);
  3677. CellReference r2 = new CellReference(null, range.getLastRow(), range.getLastColumn(), true, true);
  3678. String fmla = r1.formatAsString() + ":" + r2.formatAsString();
  3679. name.setRefersToFormula(fmla);
  3680. return new XSSFAutoFilter(this);
  3681. }
  3682. /**
  3683. * Creates a new Table, and associates it with this Sheet.
  3684. * <p>
  3685. * The table is assigned a default display name (since 4.1.1) which can be overridden
  3686. * by calling {@code setDisplayName}. The default display name is guaranteed to not conflict
  3687. * with the names of any {@code XSSFName} or {@code XSSFTable} in the workbook.
  3688. *
  3689. * @param tableArea
  3690. * the area that the table should cover, should not be null
  3691. * @return the created table
  3692. * @since 4.0.0
  3693. */
  3694. public XSSFTable createTable(AreaReference tableArea) {
  3695. if (!worksheet.isSetTableParts()) {
  3696. worksheet.addNewTableParts();
  3697. }
  3698. CTTableParts tblParts = worksheet.getTableParts();
  3699. CTTablePart tbl = tblParts.addNewTablePart();
  3700. // Table numbers need to be unique in the file, not just
  3701. // unique within the sheet. Find the next one
  3702. int tableNumber = getPackagePart().getPackage().getPartsByContentType(XSSFRelation.TABLE.getContentType()).size() + 1;
  3703. // the id could already be taken after insertion/deletion of different tables
  3704. boolean loop = true;
  3705. while(loop) {
  3706. loop = false;
  3707. for (PackagePart packagePart : getPackagePart().getPackage().getPartsByContentType(XSSFRelation.TABLE.getContentType())) {
  3708. String fileName = XSSFRelation.TABLE.getFileName(tableNumber);
  3709. if(fileName.equals(packagePart.getPartName().getName())) {
  3710. // duplicate found, increase the number and start iterating again
  3711. tableNumber++;
  3712. loop = true;
  3713. }
  3714. }
  3715. }
  3716. RelationPart rp = createRelationship(XSSFRelation.TABLE, XSSFFactory.getInstance(), tableNumber, false);
  3717. XSSFTable table = rp.getDocumentPart();
  3718. tbl.setId(rp.getRelationship().getId());
  3719. table.getCTTable().setId(tableNumber);
  3720. tables.put(tbl.getId(), table);
  3721. if(tableArea != null) {
  3722. table.setArea(tableArea);
  3723. }
  3724. // Set the default name of the table. This must not conflict with any defined names.
  3725. while(tableNumber<Integer.MAX_VALUE) {
  3726. final String displayName="Table"+tableNumber;
  3727. if(getWorkbook().getTable(displayName) == null &&
  3728. getWorkbook().getName(displayName) == null) {
  3729. table.setDisplayName(displayName);
  3730. table.setName(displayName);
  3731. break;
  3732. }
  3733. ++tableNumber;
  3734. }
  3735. return table;
  3736. }
  3737. /**
  3738. * Returns any tables associated with this Sheet
  3739. */
  3740. public List<XSSFTable> getTables() {
  3741. return new ArrayList<>(tables.values());
  3742. }
  3743. /**
  3744. * Remove table references and relations
  3745. * @param t table to remove
  3746. */
  3747. public void removeTable(XSSFTable t) {
  3748. long id = t.getCTTable().getId();
  3749. Map.Entry<String, XSSFTable> toDelete = null;
  3750. for (Map.Entry<String, XSSFTable> entry : tables.entrySet()) {
  3751. if (entry.getValue().getCTTable().getId() == id) toDelete = entry;
  3752. }
  3753. if (toDelete != null) {
  3754. removeRelation(getRelationById(toDelete.getKey()), true);
  3755. tables.remove(toDelete.getKey());
  3756. toDelete.getValue().onTableDelete();
  3757. }
  3758. }
  3759. @Override
  3760. public XSSFSheetConditionalFormatting getSheetConditionalFormatting(){
  3761. return new XSSFSheetConditionalFormatting(this);
  3762. }
  3763. /**
  3764. * Get background color of the sheet tab.
  3765. * Returns <tt>null</tt> if no sheet tab color is set.
  3766. *
  3767. * @return the background color of the sheet tab
  3768. */
  3769. public XSSFColor getTabColor() {
  3770. CTSheetPr pr = worksheet.getSheetPr();
  3771. if(pr == null) {
  3772. pr = worksheet.addNewSheetPr();
  3773. }
  3774. if (!pr.isSetTabColor()) {
  3775. return null;
  3776. }
  3777. return XSSFColor.from(pr.getTabColor(), getWorkbook().getStylesSource().getIndexedColors());
  3778. }
  3779. /**
  3780. * Set background color of the sheet tab
  3781. *
  3782. * @param color the color to set
  3783. */
  3784. public void setTabColor(XSSFColor color) {
  3785. CTSheetPr pr = worksheet.getSheetPr();
  3786. if(pr == null) {
  3787. pr = worksheet.addNewSheetPr();
  3788. }
  3789. pr.setTabColor(color.getCTColor());
  3790. }
  3791. @Override
  3792. public CellRangeAddress getRepeatingRows() {
  3793. return getRepeatingRowsOrColums(true);
  3794. }
  3795. @Override
  3796. public CellRangeAddress getRepeatingColumns() {
  3797. return getRepeatingRowsOrColums(false);
  3798. }
  3799. @Override
  3800. public void setRepeatingRows(CellRangeAddress rowRangeRef) {
  3801. CellRangeAddress columnRangeRef = getRepeatingColumns();
  3802. setRepeatingRowsAndColumns(rowRangeRef, columnRangeRef);
  3803. }
  3804. @Override
  3805. public void setRepeatingColumns(CellRangeAddress columnRangeRef) {
  3806. CellRangeAddress rowRangeRef = getRepeatingRows();
  3807. setRepeatingRowsAndColumns(rowRangeRef, columnRangeRef);
  3808. }
  3809. private void setRepeatingRowsAndColumns(
  3810. CellRangeAddress rowDef, CellRangeAddress colDef) {
  3811. int col1 = -1;
  3812. int col2 = -1;
  3813. int row1 = -1;
  3814. int row2 = -1;
  3815. if (rowDef != null) {
  3816. row1 = rowDef.getFirstRow();
  3817. row2 = rowDef.getLastRow();
  3818. if ((row1 == -1 && row2 != -1)
  3819. || row1 < -1 || row2 < -1 || row1 > row2) {
  3820. throw new IllegalArgumentException("Invalid row range specification");
  3821. }
  3822. }
  3823. if (colDef != null) {
  3824. col1 = colDef.getFirstColumn();
  3825. col2 = colDef.getLastColumn();
  3826. if ((col1 == -1 && col2 != -1)
  3827. || col1 < -1 || col2 < -1 || col1 > col2) {
  3828. throw new IllegalArgumentException(
  3829. "Invalid column range specification");
  3830. }
  3831. }
  3832. int sheetIndex = getWorkbook().getSheetIndex(this);
  3833. boolean removeAll = rowDef == null && colDef == null;
  3834. XSSFName name = getWorkbook().getBuiltInName(
  3835. XSSFName.BUILTIN_PRINT_TITLE, sheetIndex);
  3836. if (removeAll) {
  3837. if (name != null) {
  3838. getWorkbook().removeName(name);
  3839. }
  3840. return;
  3841. }
  3842. if (name == null) {
  3843. name = getWorkbook().createBuiltInName(
  3844. XSSFName.BUILTIN_PRINT_TITLE, sheetIndex);
  3845. }
  3846. String reference = getReferenceBuiltInRecord(
  3847. name.getSheetName(), col1, col2, row1, row2);
  3848. name.setRefersToFormula(reference);
  3849. // If the print setup isn't currently defined, then add it
  3850. // in but without printer defaults
  3851. // If it's already there, leave it as-is!
  3852. if (worksheet.isSetPageSetup() && worksheet.isSetPageMargins()) {
  3853. // Everything we need is already there
  3854. } else {
  3855. // Have initial ones put in place
  3856. getPrintSetup().setValidSettings(false);
  3857. }
  3858. }
  3859. private static String getReferenceBuiltInRecord(
  3860. String sheetName, int startC, int endC, int startR, int endR) {
  3861. // Excel example for built-in title:
  3862. // 'second sheet'!$E:$F,'second sheet'!$2:$3
  3863. CellReference colRef =
  3864. new CellReference(sheetName, 0, startC, true, true);
  3865. CellReference colRef2 =
  3866. new CellReference(sheetName, 0, endC, true, true);
  3867. CellReference rowRef =
  3868. new CellReference(sheetName, startR, 0, true, true);
  3869. CellReference rowRef2 =
  3870. new CellReference(sheetName, endR, 0, true, true);
  3871. String escapedName = SheetNameFormatter.format(sheetName);
  3872. String c = "";
  3873. String r = "";
  3874. if (startC != -1 || endC != -1) {
  3875. String col1 = colRef.getCellRefParts()[2];
  3876. String col2 = colRef2.getCellRefParts()[2];
  3877. c = escapedName + "!$" + col1 + ":$" + col2;
  3878. }
  3879. if (startR != -1 || endR != -1) {
  3880. String row1 = rowRef.getCellRefParts()[1];
  3881. String row2 = rowRef2.getCellRefParts()[1];
  3882. if (!row1.equals("0") && !row2.equals("0")) {
  3883. r = escapedName + "!$" + row1 + ":$" + row2;
  3884. }
  3885. }
  3886. StringBuilder rng = new StringBuilder();
  3887. rng.append(c);
  3888. if(rng.length() > 0 && r.length() > 0) {
  3889. rng.append(',');
  3890. }
  3891. rng.append(r);
  3892. return rng.toString();
  3893. }
  3894. private CellRangeAddress getRepeatingRowsOrColums(boolean rows) {
  3895. int sheetIndex = getWorkbook().getSheetIndex(this);
  3896. XSSFName name = getWorkbook().getBuiltInName(
  3897. XSSFName.BUILTIN_PRINT_TITLE, sheetIndex);
  3898. if (name == null ) {
  3899. return null;
  3900. }
  3901. String refStr = name.getRefersToFormula();
  3902. if (refStr == null) {
  3903. return null;
  3904. }
  3905. String[] parts = refStr.split(",");
  3906. int maxRowIndex = SpreadsheetVersion.EXCEL2007.getLastRowIndex();
  3907. int maxColIndex = SpreadsheetVersion.EXCEL2007.getLastColumnIndex();
  3908. for (String part : parts) {
  3909. CellRangeAddress range = CellRangeAddress.valueOf(part);
  3910. if ((range.getFirstColumn() == 0
  3911. && range.getLastColumn() == maxColIndex)
  3912. || (range.getFirstColumn() == -1
  3913. && range.getLastColumn() == -1)) {
  3914. if (rows) {
  3915. return range;
  3916. }
  3917. } else if (range.getFirstRow() == 0
  3918. && range.getLastRow() == maxRowIndex
  3919. || (range.getFirstRow() == -1
  3920. && range.getLastRow() == -1)) {
  3921. if (!rows) {
  3922. return range;
  3923. }
  3924. }
  3925. }
  3926. return null;
  3927. }
  3928. /**
  3929. * Creates an empty XSSFPivotTable and sets up all its relationships
  3930. * including: pivotCacheDefinition, pivotCacheRecords
  3931. * @return returns a pivotTable
  3932. */
  3933. @Beta
  3934. private XSSFPivotTable createPivotTable() {
  3935. XSSFWorkbook wb = getWorkbook();
  3936. List<XSSFPivotTable> pivotTables = wb.getPivotTables();
  3937. int tableId = getWorkbook().getPivotTables().size()+1;
  3938. //Create relationship between pivotTable and the worksheet
  3939. XSSFPivotTable pivotTable = (XSSFPivotTable) createRelationship(XSSFRelation.PIVOT_TABLE,
  3940. XSSFFactory.getInstance(), tableId);
  3941. pivotTable.setParentSheet(this);
  3942. pivotTables.add(pivotTable);
  3943. XSSFWorkbook workbook = getWorkbook();
  3944. //Create relationship between the pivot cache defintion and the workbook
  3945. XSSFPivotCacheDefinition pivotCacheDefinition = (XSSFPivotCacheDefinition) workbook.
  3946. createRelationship(XSSFRelation.PIVOT_CACHE_DEFINITION, XSSFFactory.getInstance(), tableId);
  3947. String rId = workbook.getRelationId(pivotCacheDefinition);
  3948. //Create relationship between pivotTable and pivotCacheDefinition without creating a new instance
  3949. PackagePart pivotPackagePart = pivotTable.getPackagePart();
  3950. pivotPackagePart.addRelationship(pivotCacheDefinition.getPackagePart().getPartName(),
  3951. TargetMode.INTERNAL, XSSFRelation.PIVOT_CACHE_DEFINITION.getRelation());
  3952. pivotTable.setPivotCacheDefinition(pivotCacheDefinition);
  3953. //Create pivotCache and sets up it's relationship with the workbook
  3954. pivotTable.setPivotCache(new XSSFPivotCache(workbook.addPivotCache(rId)));
  3955. //Create relationship between pivotcacherecord and pivotcachedefinition
  3956. XSSFPivotCacheRecords pivotCacheRecords = (XSSFPivotCacheRecords) pivotCacheDefinition.
  3957. createRelationship(XSSFRelation.PIVOT_CACHE_RECORDS, XSSFFactory.getInstance(), tableId);
  3958. //Set relationships id for pivotCacheDefinition to pivotCacheRecords
  3959. pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().setId(pivotCacheDefinition.getRelationId(pivotCacheRecords));
  3960. wb.setPivotTables(pivotTables);
  3961. return pivotTable;
  3962. }
  3963. /**
  3964. * Create a pivot table using the AreaReference range on sourceSheet, at the given position.
  3965. * If the source reference contains a sheet name, it must match the sourceSheet
  3966. * @param source location of pivot data
  3967. * @param position A reference to the top left cell where the pivot table will start
  3968. * @param sourceSheet The sheet containing the source data, if the source reference doesn't contain a sheet name
  3969. * @throws IllegalArgumentException if source references a sheet different than sourceSheet
  3970. * @return The pivot table
  3971. */
  3972. @Beta
  3973. public XSSFPivotTable createPivotTable(final AreaReference source, CellReference position, Sheet sourceSheet) {
  3974. final String sourceSheetName = source.getFirstCell().getSheetName();
  3975. if(sourceSheetName != null && !sourceSheetName.equalsIgnoreCase(sourceSheet.getSheetName())) {
  3976. throw new IllegalArgumentException("The area is referenced in another sheet than the "
  3977. + "defined source sheet " + sourceSheet.getSheetName() + ".");
  3978. }
  3979. return createPivotTable(position, sourceSheet, wsSource -> {
  3980. final String[] firstCell = source.getFirstCell().getCellRefParts();
  3981. final String firstRow = firstCell[1];
  3982. final String firstCol = firstCell[2];
  3983. final String[] lastCell = source.getLastCell().getCellRefParts();
  3984. final String lastRow = lastCell[1];
  3985. final String lastCol = lastCell[2];
  3986. final String ref = firstCol+firstRow+':'+lastCol+lastRow; //or just source.formatAsString()
  3987. wsSource.setRef(ref);
  3988. });
  3989. }
  3990. /**
  3991. * Create a pivot table using the AreaReference or named/table range on sourceSheet, at the given position.
  3992. * If the source reference contains a sheet name, it must match the sourceSheet.
  3993. * @param position A reference to the top left cell where the pivot table will start
  3994. * @param sourceSheet The sheet containing the source data, if the source reference doesn't contain a sheet name
  3995. * @param refConfig A reference to the pivot table configurator
  3996. * @throws IllegalArgumentException if source references a sheet different than sourceSheet
  3997. * @return The pivot table
  3998. */
  3999. private XSSFPivotTable createPivotTable(CellReference position, Sheet sourceSheet, PivotTableReferenceConfigurator refConfig) {
  4000. XSSFPivotTable pivotTable = createPivotTable();
  4001. //Creates default settings for the pivot table
  4002. pivotTable.setDefaultPivotTableDefinition();
  4003. //Set sources and references
  4004. pivotTable.createSourceReferences(position, sourceSheet, refConfig);
  4005. //Create cachefield/s and empty SharedItems - must be after creating references
  4006. pivotTable.getPivotCacheDefinition().createCacheFields(sourceSheet);
  4007. pivotTable.createDefaultDataColumns();
  4008. return pivotTable;
  4009. }
  4010. /**
  4011. * Create a pivot table using the AreaReference range, at the given position.
  4012. * If the source reference contains a sheet name, that sheet is used, otherwise this sheet is assumed as the source sheet.
  4013. * @param source location of pivot data
  4014. * @param position A reference to the top left cell where the pivot table will start
  4015. * @return The pivot table
  4016. */
  4017. @Beta
  4018. public XSSFPivotTable createPivotTable(AreaReference source, CellReference position){
  4019. final String sourceSheetName = source.getFirstCell().getSheetName();
  4020. if(sourceSheetName != null && !sourceSheetName.equalsIgnoreCase(this.getSheetName())) {
  4021. final XSSFSheet sourceSheet = getWorkbook().getSheet(sourceSheetName);
  4022. return createPivotTable(source, position, sourceSheet);
  4023. }
  4024. return createPivotTable(source, position, this);
  4025. }
  4026. /**
  4027. * Create a pivot table using the Name range reference on sourceSheet, at the given position.
  4028. * If the source reference contains a sheet name, it must match the sourceSheet
  4029. * @param source location of pivot data
  4030. * @param position A reference to the top left cell where the pivot table will start
  4031. * @param sourceSheet The sheet containing the source data, if the source reference doesn't contain a sheet name
  4032. * @throws IllegalArgumentException if source references a sheet different than sourceSheet
  4033. * @return The pivot table
  4034. */
  4035. @Beta
  4036. public XSSFPivotTable createPivotTable(final Name source, CellReference position, Sheet sourceSheet) {
  4037. if(source.getSheetName() != null && !source.getSheetName().equals(sourceSheet.getSheetName())) {
  4038. throw new IllegalArgumentException("The named range references another sheet than the "
  4039. + "defined source sheet " + sourceSheet.getSheetName() + ".");
  4040. }
  4041. return createPivotTable(position, sourceSheet, wsSource -> wsSource.setName(source.getNameName()));
  4042. }
  4043. /**
  4044. * Create a pivot table using the Name range, at the given position.
  4045. * If the source reference contains a sheet name, that sheet is used, otherwise this sheet is assumed as the source sheet.
  4046. * @param source location of pivot data
  4047. * @param position A reference to the top left cell where the pivot table will start
  4048. * @return The pivot table
  4049. */
  4050. @Beta
  4051. public XSSFPivotTable createPivotTable(Name source, CellReference position) {
  4052. return createPivotTable(source, position, getWorkbook().getSheet(source.getSheetName()));
  4053. }
  4054. /**
  4055. * Create a pivot table using the Table, at the given position.
  4056. * Tables are required to have a sheet reference, so no additional logic around reference sheet is needed.
  4057. * @param source location of pivot data
  4058. * @param position A reference to the top left cell where the pivot table will start
  4059. * @return The pivot table
  4060. */
  4061. @Beta
  4062. public XSSFPivotTable createPivotTable(final Table source, CellReference position) {
  4063. return createPivotTable(position, getWorkbook().getSheet(source.getSheetName()), wsSource -> wsSource.setName(source.getName()));
  4064. }
  4065. /**
  4066. * Returns all the pivot tables for this Sheet
  4067. */
  4068. @Beta
  4069. public List<XSSFPivotTable> getPivotTables() {
  4070. List<XSSFPivotTable> tables = new ArrayList<>();
  4071. for (XSSFPivotTable table : getWorkbook().getPivotTables()) {
  4072. if (table.getParent() == this) {
  4073. tables.add(table);
  4074. }
  4075. }
  4076. return tables;
  4077. }
  4078. @Override
  4079. public int getColumnOutlineLevel(int columnIndex) {
  4080. CTCol col = columnHelper.getColumn(columnIndex, false);
  4081. if (col == null) {
  4082. return 0;
  4083. }
  4084. return col.getOutlineLevel();
  4085. }
  4086. /**
  4087. * Add ignored errors (usually to suppress them in the UI of a consuming
  4088. * application).
  4089. *
  4090. * @param cell Cell.
  4091. * @param ignoredErrorTypes Types of error to ignore there.
  4092. */
  4093. public void addIgnoredErrors(CellReference cell, IgnoredErrorType... ignoredErrorTypes) {
  4094. addIgnoredErrors(cell.formatAsString(false), ignoredErrorTypes);
  4095. }
  4096. /**
  4097. * Ignore errors across a range of cells.
  4098. *
  4099. * @param region Range of cells.
  4100. * @param ignoredErrorTypes Types of error to ignore there.
  4101. */
  4102. public void addIgnoredErrors(CellRangeAddress region, IgnoredErrorType... ignoredErrorTypes) {
  4103. region.validate(SpreadsheetVersion.EXCEL2007);
  4104. addIgnoredErrors(region.formatAsString(), ignoredErrorTypes);
  4105. }
  4106. /**
  4107. * Returns the errors currently being ignored and the ranges
  4108. * where they are ignored.
  4109. *
  4110. * @return Map of error type to the range(s) where they are ignored.
  4111. */
  4112. public Map<IgnoredErrorType, Set<CellRangeAddress>> getIgnoredErrors() {
  4113. Map<IgnoredErrorType, Set<CellRangeAddress>> result = new LinkedHashMap<>();
  4114. if (worksheet.isSetIgnoredErrors()) {
  4115. for (CTIgnoredError err : worksheet.getIgnoredErrors().getIgnoredErrorList()) {
  4116. for (IgnoredErrorType errType : XSSFIgnoredErrorHelper.getErrorTypes(err)) {
  4117. if (!result.containsKey(errType)) {
  4118. result.put(errType, new LinkedHashSet<>());
  4119. }
  4120. for (Object ref : err.getSqref()) {
  4121. result.get(errType).add(CellRangeAddress.valueOf(ref.toString()));
  4122. }
  4123. }
  4124. }
  4125. }
  4126. return result;
  4127. }
  4128. private void addIgnoredErrors(String ref, IgnoredErrorType... ignoredErrorTypes) {
  4129. CTIgnoredErrors ctIgnoredErrors = worksheet.isSetIgnoredErrors() ? worksheet.getIgnoredErrors() : worksheet.addNewIgnoredErrors();
  4130. CTIgnoredError ctIgnoredError = ctIgnoredErrors.addNewIgnoredError();
  4131. XSSFIgnoredErrorHelper.addIgnoredErrors(ctIgnoredError, ref, ignoredErrorTypes);
  4132. }
  4133. /**
  4134. * called when a sheet is being deleted/removed from a workbook, to clean up relations and other document pieces tied to the sheet
  4135. */
  4136. protected void onSheetDelete() {
  4137. for (RelationPart part : getRelationParts()) {
  4138. if (part.getDocumentPart() instanceof XSSFTable) {
  4139. // call table delete
  4140. removeTable(part.getDocumentPart());
  4141. continue;
  4142. }
  4143. removeRelation(part.getDocumentPart(), true);
  4144. }
  4145. }
  4146. /**
  4147. * when a cell with a 'master' shared formula is removed, the next cell in the range becomes the master
  4148. * @param cell The cell that is removed
  4149. * @param evalWb BaseXSSFEvaluationWorkbook in use, if one exists
  4150. */
  4151. protected void onDeleteFormula(XSSFCell cell, BaseXSSFEvaluationWorkbook evalWb){
  4152. CTCellFormula f = cell.getCTCell().getF();
  4153. if (f != null && f.getT() == STCellFormulaType.SHARED && f.isSetRef() && f.getStringValue() != null) {
  4154. CellRangeAddress ref = CellRangeAddress.valueOf(f.getRef());
  4155. if(ref.getNumberOfCells() > 1){
  4156. DONE:
  4157. for(int i = cell.getRowIndex(); i <= ref.getLastRow(); i++){
  4158. XSSFRow row = getRow(i);
  4159. if(row != null) for(int j = cell.getColumnIndex(); j <= ref.getLastColumn(); j++){
  4160. XSSFCell nextCell = row.getCell(j);
  4161. if(nextCell != null && nextCell != cell && nextCell.getCellType() == CellType.FORMULA){
  4162. CTCellFormula nextF = nextCell.getCTCell().getF();
  4163. nextF.setStringValue(nextCell.getCellFormula(evalWb));
  4164. CellRangeAddress nextRef = new CellRangeAddress(
  4165. nextCell.getRowIndex(), ref.getLastRow(),
  4166. nextCell.getColumnIndex(), ref.getLastColumn());
  4167. nextF.setRef(nextRef.formatAsString());
  4168. sharedFormulas.put(Math.toIntExact(nextF.getSi()), nextF);
  4169. break DONE;
  4170. }
  4171. }
  4172. }
  4173. }
  4174. }
  4175. }
  4176. /**
  4177. * Determine the OleObject which links shapes with embedded resources
  4178. *
  4179. * @param shapeId the shape id
  4180. * @return the CTOleObject of the shape
  4181. */
  4182. protected CTOleObject readOleObject(long shapeId) {
  4183. if (!getCTWorksheet().isSetOleObjects()) {
  4184. return null;
  4185. }
  4186. // we use a XmlCursor here to handle oleObject with-/out AlternateContent wrappers
  4187. String xquery = "declare namespace p='"+XSSFRelation.NS_SPREADSHEETML+"' .//p:oleObject";
  4188. XmlCursor cur = getCTWorksheet().getOleObjects().newCursor();
  4189. try {
  4190. cur.selectPath(xquery);
  4191. CTOleObject coo = null;
  4192. while (cur.toNextSelection()) {
  4193. String sId = cur.getAttributeText(new QName(null, "shapeId"));
  4194. if (sId == null || Long.parseLong(sId) != shapeId) {
  4195. continue;
  4196. }
  4197. XmlObject xObj = cur.getObject();
  4198. if (xObj instanceof CTOleObject) {
  4199. // the unusual case ...
  4200. coo = (CTOleObject)xObj;
  4201. } else {
  4202. XMLStreamReader reader = cur.newXMLStreamReader();
  4203. try {
  4204. CTOleObjects coos = CTOleObjects.Factory.parse(reader);
  4205. if (coos.sizeOfOleObjectArray() == 0) {
  4206. continue;
  4207. }
  4208. coo = coos.getOleObjectArray(0);
  4209. } catch (XmlException e) {
  4210. logger.log(POILogger.INFO, "can't parse CTOleObjects", e);
  4211. } finally {
  4212. try {
  4213. reader.close();
  4214. } catch (XMLStreamException e) {
  4215. logger.log(POILogger.INFO, "can't close reader", e);
  4216. }
  4217. }
  4218. }
  4219. // there are choice and fallback OleObject ... we prefer the one having the objectPr element,
  4220. // which is in the choice element
  4221. if (cur.toChild(XSSFRelation.NS_SPREADSHEETML, "objectPr")) {
  4222. break;
  4223. }
  4224. }
  4225. return coo;
  4226. } finally {
  4227. cur.dispose();
  4228. }
  4229. }
  4230. public XSSFHeaderFooterProperties getHeaderFooterProperties() {
  4231. return new XSSFHeaderFooterProperties(getSheetTypeHeaderFooter());
  4232. }
  4233. }