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

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