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

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