You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

XSSFSheet.java 178KB

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