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

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