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

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