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

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