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 177KB

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