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

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