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

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