Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

XSSFSheet.java 170KB

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