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

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