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

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