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

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