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

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