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.

HSSFSheet.java 93KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699
  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.hssf.usermodel;
  16. import java.io.PrintWriter;
  17. import java.util.ArrayList;
  18. import java.util.Collection;
  19. import java.util.Iterator;
  20. import java.util.List;
  21. import java.util.Map;
  22. import java.util.Spliterator;
  23. import java.util.TreeMap;
  24. import java.util.TreeSet;
  25. import org.apache.logging.log4j.LogManager;
  26. import org.apache.logging.log4j.Logger;
  27. import org.apache.logging.log4j.message.SimpleMessage;
  28. import org.apache.poi.ddf.EscherRecord;
  29. import org.apache.poi.hssf.model.DrawingManager2;
  30. import org.apache.poi.hssf.model.HSSFFormulaParser;
  31. import org.apache.poi.hssf.model.InternalSheet;
  32. import org.apache.poi.hssf.model.InternalWorkbook;
  33. import org.apache.poi.hssf.record.AutoFilterInfoRecord;
  34. import org.apache.poi.hssf.record.CellValueRecordInterface;
  35. import org.apache.poi.hssf.record.DVRecord;
  36. import org.apache.poi.hssf.record.DimensionsRecord;
  37. import org.apache.poi.hssf.record.DrawingRecord;
  38. import org.apache.poi.hssf.record.EscherAggregate;
  39. import org.apache.poi.hssf.record.ExtendedFormatRecord;
  40. import org.apache.poi.hssf.record.HyperlinkRecord;
  41. import org.apache.poi.hssf.record.NameRecord;
  42. import org.apache.poi.hssf.record.Record;
  43. import org.apache.poi.hssf.record.RecordBase;
  44. import org.apache.poi.hssf.record.RowRecord;
  45. import org.apache.poi.hssf.record.SCLRecord;
  46. import org.apache.poi.hssf.record.WSBoolRecord;
  47. import org.apache.poi.hssf.record.WindowTwoRecord;
  48. import org.apache.poi.hssf.record.aggregates.DataValidityTable;
  49. import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
  50. import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor;
  51. import org.apache.poi.hssf.record.aggregates.WorksheetProtectionBlock;
  52. import org.apache.poi.hssf.usermodel.helpers.HSSFColumnShifter;
  53. import org.apache.poi.hssf.usermodel.helpers.HSSFRowShifter;
  54. import org.apache.poi.ss.SpreadsheetVersion;
  55. import org.apache.poi.ss.formula.FormulaShifter;
  56. import org.apache.poi.ss.formula.FormulaType;
  57. import org.apache.poi.ss.formula.ptg.Area3DPtg;
  58. import org.apache.poi.ss.formula.ptg.MemFuncPtg;
  59. import org.apache.poi.ss.formula.ptg.Ptg;
  60. import org.apache.poi.ss.formula.ptg.UnionPtg;
  61. import org.apache.poi.ss.usermodel.Cell;
  62. import org.apache.poi.ss.usermodel.CellRange;
  63. import org.apache.poi.ss.usermodel.CellStyle;
  64. import org.apache.poi.ss.usermodel.DataValidation;
  65. import org.apache.poi.ss.usermodel.DataValidationHelper;
  66. import org.apache.poi.ss.usermodel.FormulaEvaluator;
  67. import org.apache.poi.ss.usermodel.Row;
  68. import org.apache.poi.ss.usermodel.Sheet;
  69. import org.apache.poi.ss.usermodel.Workbook;
  70. import org.apache.poi.ss.usermodel.helpers.RowShifter;
  71. import org.apache.poi.ss.util.CellAddress;
  72. import org.apache.poi.ss.util.CellRangeAddress;
  73. import org.apache.poi.ss.util.CellRangeAddressList;
  74. import org.apache.poi.ss.util.CellReference;
  75. import org.apache.poi.ss.util.PaneInformation;
  76. import org.apache.poi.ss.util.SSCellRange;
  77. import org.apache.poi.ss.util.SheetUtil;
  78. import org.apache.poi.util.Beta;
  79. import org.apache.poi.util.Configurator;
  80. import org.apache.poi.util.Internal;
  81. import static java.lang.System.currentTimeMillis;
  82. import static org.apache.logging.log4j.util.Unbox.box;
  83. /**
  84. * High level representation of a worksheet.
  85. */
  86. public final class HSSFSheet implements Sheet {
  87. private static final Logger LOGGER = LogManager.getLogger(HSSFSheet.class);
  88. /**
  89. * width of 1px in columns with default width in units of 1/256 of a character width
  90. */
  91. private static final float PX_DEFAULT = 32.00f;
  92. /**
  93. * width of 1px in columns with overridden width in units of 1/256 of a character width
  94. */
  95. private static final float PX_MODIFIED = 36.56f;
  96. /**
  97. * Used for compile-time optimization. This is the initial size for the collection of
  98. * rows. It is currently set to 20. If you generate larger sheets you may benefit
  99. * by setting this to a higher number and recompiling a custom edition of HSSFSheet.
  100. */
  101. public static final int INITIAL_CAPACITY = Configurator.getIntValue("HSSFSheet.RowInitialCapacity", 20);
  102. /**
  103. * reference to the low level {@link InternalSheet} object
  104. */
  105. private final InternalSheet _sheet;
  106. /**
  107. * stores rows by zero-based row number
  108. */
  109. private final TreeMap<Integer, HSSFRow> _rows;
  110. protected final InternalWorkbook _book;
  111. protected final HSSFWorkbook _workbook;
  112. private HSSFPatriarch _patriarch;
  113. private int _firstrow = -1;
  114. private int _lastrow = -1;
  115. /**
  116. * Creates new HSSFSheet - called by HSSFWorkbook to create a sheet from
  117. * scratch. You should not be calling this from application code (its protected anyhow).
  118. *
  119. * @param workbook - The HSSF Workbook object associated with the sheet.
  120. * @see HSSFWorkbook#createSheet()
  121. */
  122. protected HSSFSheet(HSSFWorkbook workbook) {
  123. _sheet = InternalSheet.createSheet();
  124. _rows = new TreeMap<>();
  125. this._workbook = workbook;
  126. this._book = workbook.getWorkbook();
  127. }
  128. /**
  129. * Creates an HSSFSheet representing the given Sheet object. Should only be
  130. * called by HSSFWorkbook when reading in an exisiting file.
  131. *
  132. * @param workbook - The HSSF Workbook object associated with the sheet.
  133. * @param sheet - lowlevel Sheet object this sheet will represent
  134. * @see HSSFWorkbook#createSheet()
  135. */
  136. protected HSSFSheet(HSSFWorkbook workbook, InternalSheet sheet) {
  137. this._sheet = sheet;
  138. _rows = new TreeMap<>();
  139. this._workbook = workbook;
  140. this._book = workbook.getWorkbook();
  141. setPropertiesFromSheet(sheet);
  142. }
  143. HSSFSheet cloneSheet(HSSFWorkbook workbook) {
  144. // Aggregate drawing records
  145. this.getDrawingPatriarch();
  146. HSSFSheet sheet = new HSSFSheet(workbook, _sheet.cloneSheet());
  147. int pos = sheet._sheet.findFirstRecordLocBySid(DrawingRecord.sid);
  148. DrawingRecord dr = (DrawingRecord) sheet._sheet.findFirstRecordBySid(DrawingRecord.sid);
  149. if (null != dr) {
  150. sheet._sheet.getRecords().remove(dr);
  151. }
  152. if (getDrawingPatriarch() != null) {
  153. HSSFPatriarch patr = HSSFPatriarch.createPatriarch(this.getDrawingPatriarch(), sheet);
  154. sheet._sheet.getRecords().add(pos, patr.getBoundAggregate());
  155. sheet._patriarch = patr;
  156. }
  157. return sheet;
  158. }
  159. /**
  160. * check whether the data of sheet can be serialized
  161. */
  162. protected void preSerialize(){
  163. if (_patriarch != null){
  164. _patriarch.preSerialize();
  165. }
  166. }
  167. /**
  168. * Return the parent workbook
  169. *
  170. * @return the parent workbook
  171. */
  172. @Override
  173. public HSSFWorkbook getWorkbook() {
  174. return _workbook;
  175. }
  176. /**
  177. * used internally to set the properties given a Sheet object
  178. */
  179. private void setPropertiesFromSheet(InternalSheet sheet) {
  180. RowRecord row = sheet.getNextRow();
  181. while (row != null) {
  182. createRowFromRecord(row);
  183. row = sheet.getNextRow();
  184. }
  185. Iterator<CellValueRecordInterface> iter = sheet.getCellValueIterator();
  186. long timestart = currentTimeMillis();
  187. LOGGER.atDebug().log("Time at start of cell creating in HSSF sheet = {}", box(timestart));
  188. HSSFRow lastrow = null;
  189. // Add every cell to its row
  190. while (iter.hasNext()) {
  191. CellValueRecordInterface cval = iter.next();
  192. long cellstart = currentTimeMillis();
  193. HSSFRow hrow = lastrow;
  194. if (hrow == null || hrow.getRowNum() != cval.getRow()) {
  195. hrow = getRow(cval.getRow());
  196. lastrow = hrow;
  197. if (hrow == null) {
  198. /* we removed this check, see bug 47245 for the discussion around this
  199. // Some tools (like Perl module Spreadsheet::WriteExcel - bug 41187) skip the RowRecords
  200. // Excel, OpenOffice.org and GoogleDocs are all OK with this, so POI should be too.
  201. if (rowRecordsAlreadyPresent) {
  202. // if at least one row record is present, all should be present.
  203. throw new RuntimeException("Unexpected missing row when some rows already present");
  204. }*/
  205. // create the row record on the fly now.
  206. RowRecord rowRec = new RowRecord(cval.getRow());
  207. sheet.addRow(rowRec);
  208. hrow = createRowFromRecord(rowRec);
  209. }
  210. }
  211. LOGGER.atTrace().log(() -> {
  212. if (cval instanceof Record) {
  213. return new SimpleMessage("record id = " + Integer.toHexString(((Record) cval).getSid()));
  214. } else {
  215. return new SimpleMessage("record = " + cval);
  216. }
  217. });
  218. hrow.createCellFromRecord( cval );
  219. LOGGER.atTrace().log("record took {}ms", box(currentTimeMillis() - cellstart));
  220. }
  221. LOGGER.atDebug().log("total sheet cell creation took {}ms", box(currentTimeMillis() - timestart));
  222. }
  223. /**
  224. * Create a new row within the sheet and return the high level representation
  225. *
  226. * @param rownum row number
  227. * @return High level HSSFRow object representing a row in the sheet
  228. * @see HSSFRow
  229. * @see #removeRow(Row)
  230. */
  231. @Override
  232. public HSSFRow createRow(int rownum) {
  233. HSSFRow row = new HSSFRow(_workbook, this, rownum);
  234. // new rows inherit default height from the sheet
  235. row.setHeight(getDefaultRowHeight());
  236. row.getRowRecord().setBadFontHeight(false);
  237. addRow(row, true);
  238. return row;
  239. }
  240. /**
  241. * Used internally to create a high level Row object from a low level row object.
  242. * USed when reading an existing file
  243. *
  244. * @param row low level record to represent as a high level Row and add to sheet
  245. * @return HSSFRow high level representation
  246. */
  247. private HSSFRow createRowFromRecord(RowRecord row) {
  248. HSSFRow hrow = new HSSFRow(_workbook, this, row);
  249. addRow(hrow, false);
  250. return hrow;
  251. }
  252. /**
  253. * Remove a row from this sheet. All cells contained in the row are removed as well
  254. *
  255. * @param row representing a row to remove.
  256. */
  257. @Override
  258. public void removeRow(Row row) {
  259. HSSFRow hrow = (HSSFRow) row;
  260. if (row.getSheet() != this) {
  261. throw new IllegalArgumentException("Specified row does not belong to this sheet");
  262. }
  263. for (Cell cell : row) {
  264. HSSFCell xcell = (HSSFCell) cell;
  265. if (xcell.isPartOfArrayFormulaGroup()) {
  266. String msg = "Row[rownum=" + row.getRowNum() + "] contains cell(s) included in a multi-cell array formula. You cannot change part of an array.";
  267. xcell.tryToDeleteArrayFormula(msg);
  268. }
  269. }
  270. if (_rows.size() > 0) {
  271. Integer key = Integer.valueOf(row.getRowNum());
  272. HSSFRow removedRow = _rows.remove(key);
  273. if (removedRow != row) {
  274. //should not happen if the input argument is valid
  275. throw new IllegalArgumentException("Specified row does not belong to this sheet");
  276. }
  277. if (hrow.getRowNum() == getLastRowNum()) {
  278. _lastrow = findLastRow(_lastrow);
  279. }
  280. if (hrow.getRowNum() == getFirstRowNum()) {
  281. _firstrow = findFirstRow(_firstrow);
  282. }
  283. _sheet.removeRow(hrow.getRowRecord());
  284. // if there are no more rows, then reset first/last
  285. if(_rows.size() == 0) {
  286. _firstrow = -1;
  287. _lastrow = -1;
  288. }
  289. }
  290. }
  291. /**
  292. * used internally to refresh the "last row" when the last row is removed.
  293. */
  294. private int findLastRow(int lastrow) {
  295. if (lastrow < 1) {
  296. return 0;
  297. }
  298. int rownum = lastrow - 1;
  299. HSSFRow r = getRow(rownum);
  300. while (r == null && rownum > 0) {
  301. r = getRow(--rownum);
  302. }
  303. if (r == null) {
  304. return 0;
  305. }
  306. return rownum;
  307. }
  308. /**
  309. * used internally to refresh the "first row" when the first row is removed.
  310. */
  311. private int findFirstRow(int firstrow) {
  312. int rownum = firstrow + 1;
  313. HSSFRow r = getRow(rownum);
  314. while (r == null && rownum <= getLastRowNum()) {
  315. r = getRow(++rownum);
  316. }
  317. if (rownum > getLastRowNum())
  318. return 0;
  319. return rownum;
  320. }
  321. /**
  322. * add a row to the sheet
  323. *
  324. * @param addLow whether to add the row to the low level model - false if its already there
  325. */
  326. private void addRow(HSSFRow row, boolean addLow) {
  327. _rows.put(Integer.valueOf(row.getRowNum()), row);
  328. if (addLow) {
  329. _sheet.addRow(row.getRowRecord());
  330. }
  331. boolean firstRow = _rows.size() == 1;
  332. if (row.getRowNum() > getLastRowNum() || firstRow) {
  333. _lastrow = row.getRowNum();
  334. }
  335. if (row.getRowNum() < getFirstRowNum() || firstRow) {
  336. _firstrow = row.getRowNum();
  337. }
  338. }
  339. /**
  340. * Returns the logical row (not physical) 0-based. If you ask for a row that is not
  341. * defined you get a null. This is to say row 4 represents the fifth row on a sheet.
  342. *
  343. * @param rowIndex row to get
  344. * @return HSSFRow representing the row number or null if its not defined on the sheet
  345. */
  346. @Override
  347. public HSSFRow getRow(int rowIndex) {
  348. return _rows.get(Integer.valueOf(rowIndex));
  349. }
  350. /**
  351. * Returns the number of physically defined rows (NOT the number of rows in the sheet)
  352. */
  353. @Override
  354. public int getPhysicalNumberOfRows() {
  355. return _rows.size();
  356. }
  357. /**
  358. * Gets the first row on the sheet
  359. *
  360. * @return the number of the first logical row on the sheet, zero based
  361. */
  362. @Override
  363. public int getFirstRowNum() {
  364. return _firstrow;
  365. }
  366. /**
  367. * Gets the number last row on the sheet.
  368. * Owing to idiosyncrasies in the excel file
  369. * format, if the result of calling this method
  370. * is zero, you can't tell if that means there
  371. * are zero rows on the sheet, or one at
  372. * position zero. For that case, additionally
  373. * call {@link #getPhysicalNumberOfRows()} to
  374. * tell if there is a row at position zero
  375. * or not.
  376. *
  377. * @return the number of the last row contained in this sheet, zero based.
  378. */
  379. @Override
  380. public int getLastRowNum() {
  381. return _lastrow;
  382. }
  383. @Override
  384. public List<HSSFDataValidation> getDataValidations() {
  385. DataValidityTable dvt = _sheet.getOrCreateDataValidityTable();
  386. final List<HSSFDataValidation> hssfValidations = new ArrayList<>();
  387. RecordVisitor visitor = new RecordVisitor() {
  388. private HSSFEvaluationWorkbook book = HSSFEvaluationWorkbook.create(getWorkbook());
  389. @Override
  390. public void visitRecord(Record r) {
  391. if (!(r instanceof DVRecord)) {
  392. return;
  393. }
  394. DVRecord dvRecord = (DVRecord) r;
  395. CellRangeAddressList regions = dvRecord.getCellRangeAddress().copy();
  396. DVConstraint constraint = DVConstraint.createDVConstraint(dvRecord, book);
  397. HSSFDataValidation hssfDataValidation = new HSSFDataValidation(regions, constraint);
  398. hssfDataValidation.setErrorStyle(dvRecord.getErrorStyle());
  399. hssfDataValidation.setEmptyCellAllowed(dvRecord.getEmptyCellAllowed());
  400. hssfDataValidation.setSuppressDropDownArrow(dvRecord.getSuppressDropdownArrow());
  401. hssfDataValidation.createPromptBox(dvRecord.getPromptTitle(), dvRecord.getPromptText());
  402. hssfDataValidation.setShowPromptBox(dvRecord.getShowPromptOnCellSelected());
  403. hssfDataValidation.createErrorBox(dvRecord.getErrorTitle(), dvRecord.getErrorText());
  404. hssfDataValidation.setShowErrorBox(dvRecord.getShowErrorOnInvalidValue());
  405. hssfValidations.add(hssfDataValidation);
  406. }
  407. };
  408. dvt.visitContainedRecords(visitor);
  409. return hssfValidations;
  410. }
  411. /**
  412. * Creates a data validation object
  413. *
  414. * @param dataValidation The Data validation object settings
  415. */
  416. @Override
  417. public void addValidationData(DataValidation dataValidation) {
  418. if (dataValidation == null) {
  419. throw new IllegalArgumentException("objValidation must not be null");
  420. }
  421. HSSFDataValidation hssfDataValidation = (HSSFDataValidation) dataValidation;
  422. DataValidityTable dvt = _sheet.getOrCreateDataValidityTable();
  423. DVRecord dvRecord = hssfDataValidation.createDVRecord(this);
  424. dvt.addDataValidation(dvRecord);
  425. }
  426. /**
  427. * Get the visibility state for a given column.
  428. *
  429. * @param columnIndex - the column to get (0-based)
  430. * @param hidden - the visiblity state of the column
  431. */
  432. @Override
  433. public void setColumnHidden(int columnIndex, boolean hidden) {
  434. _sheet.setColumnHidden(columnIndex, hidden);
  435. }
  436. /**
  437. * Get the hidden state for a given column.
  438. *
  439. * @param columnIndex - the column to set (0-based)
  440. * @return hidden - <code>false</code> if the column is visible
  441. */
  442. @Override
  443. public boolean isColumnHidden(int columnIndex) {
  444. return _sheet.isColumnHidden(columnIndex);
  445. }
  446. /**
  447. * Set the width (in units of 1/256th of a character width)<p>
  448. *
  449. * The maximum column width for an individual cell is 255 characters.
  450. * This value represents the number of characters that can be displayed
  451. * in a cell that is formatted with the standard font (first font in the workbook).<p>
  452. *
  453. * Character width is defined as the maximum digit width
  454. * of the numbers <code>0, 1, 2, ... 9</code> as rendered
  455. * using the default font (first font in the workbook).<p>
  456. *
  457. * Unless you are using a very special font, the default character is '0' (zero),
  458. * this is true for Arial (default font font in HSSF) and Calibri (default font in XSSF)<p>
  459. *
  460. * Please note, that the width set by this method includes 4 pixels of margin padding (two on each side),
  461. * plus 1 pixel padding for the gridlines (Section 3.3.1.12 of the OOXML spec).
  462. * This results is a slightly less value of visible characters than passed to this method (approx. 1/2 of a character).<p>
  463. *
  464. * To compute the actual number of visible characters,
  465. * Excel uses the following formula (Section 3.3.1.12 of the OOXML spec):<p>
  466. *
  467. * <code>
  468. * width = Truncate([{Number of Visible Characters} *
  469. * {Maximum Digit Width} + {5 pixel padding}]/{Maximum Digit Width}*256)/256
  470. * </code>
  471. * <p>Using the Calibri font as an example, the maximum digit width of 11 point font size is 7 pixels (at 96 dpi).
  472. * If you set a column width to be eight characters wide, e.g. <code>setColumnWidth(columnIndex, 8*256)</code>,
  473. * then the actual value of visible characters (the value shown in Excel) is derived from the following equation:
  474. * <code>
  475. * Truncate([numChars*7+5]/7*256)/256 = 8;
  476. * </code>
  477. * <p>
  478. * which gives <code>7.29</code>.
  479. *
  480. * @param columnIndex - the column to set (0-based)
  481. * @param width - the width in units of 1/256th of a character width
  482. * @throws IllegalArgumentException if width &gt; 255*256 (the maximum column width in Excel is 255 characters)
  483. */
  484. @Override
  485. public void setColumnWidth(int columnIndex, int width) {
  486. _sheet.setColumnWidth(columnIndex, width);
  487. }
  488. /**
  489. * get the width (in units of 1/256th of a character width )
  490. *
  491. * @param columnIndex - the column to set (0-based)
  492. * @return width - the width in units of 1/256th of a character width
  493. */
  494. @Override
  495. public int getColumnWidth(int columnIndex) {
  496. return _sheet.getColumnWidth(columnIndex);
  497. }
  498. @Override
  499. public float getColumnWidthInPixels(int column){
  500. int cw = getColumnWidth(column);
  501. int def = getDefaultColumnWidth()*256;
  502. float px = (cw == def ? PX_DEFAULT : PX_MODIFIED);
  503. return cw/px;
  504. }
  505. /**
  506. * get the default column width for the sheet (if the columns do not define their own width) in
  507. * characters
  508. *
  509. * @return default column width
  510. */
  511. @Override
  512. public int getDefaultColumnWidth() {
  513. return _sheet.getDefaultColumnWidth();
  514. }
  515. /**
  516. * set the default column width for the sheet (if the columns do not define their own width) in
  517. * characters
  518. *
  519. * @param width default column width
  520. */
  521. @Override
  522. public void setDefaultColumnWidth(int width) {
  523. _sheet.setDefaultColumnWidth(width);
  524. }
  525. /**
  526. * get the default row height for the sheet (if the rows do not define their own height) in
  527. * twips (1/20 of a point)
  528. *
  529. * @return default row height
  530. */
  531. @Override
  532. public short getDefaultRowHeight() {
  533. return _sheet.getDefaultRowHeight();
  534. }
  535. /**
  536. * get the default row height for the sheet (if the rows do not define their own height) in
  537. * points.
  538. *
  539. * @return default row height in points
  540. */
  541. @Override
  542. public float getDefaultRowHeightInPoints() {
  543. return ((float) _sheet.getDefaultRowHeight() / 20);
  544. }
  545. /**
  546. * set the default row height for the sheet (if the rows do not define their own height) in
  547. * twips (1/20 of a point)
  548. *
  549. * @param height default row height
  550. */
  551. @Override
  552. public void setDefaultRowHeight(short height) {
  553. _sheet.setDefaultRowHeight(height);
  554. }
  555. /**
  556. * set the default row height for the sheet (if the rows do not define their own height) in
  557. * points
  558. *
  559. * @param height default row height
  560. */
  561. @Override
  562. public void setDefaultRowHeightInPoints(float height) {
  563. _sheet.setDefaultRowHeight((short) (height * 20));
  564. }
  565. /**
  566. * Returns the HSSFCellStyle that applies to the given
  567. * (0 based) column, or null if no style has been
  568. * set for that column
  569. */
  570. @Override
  571. public HSSFCellStyle getColumnStyle(int column) {
  572. short styleIndex = _sheet.getXFIndexForColAt((short) column);
  573. if (styleIndex == 0xf) {
  574. // None set
  575. return null;
  576. }
  577. ExtendedFormatRecord xf = _book.getExFormatAt(styleIndex);
  578. return new HSSFCellStyle(styleIndex, xf, _book);
  579. }
  580. /**
  581. * get whether gridlines are printed.
  582. *
  583. * @return true if printed
  584. */
  585. public boolean isGridsPrinted() {
  586. return _sheet.isGridsPrinted();
  587. }
  588. /**
  589. * set whether gridlines printed.
  590. *
  591. * @param value false if not printed.
  592. */
  593. public void setGridsPrinted(boolean value) {
  594. _sheet.setGridsPrinted(value);
  595. }
  596. /**
  597. * Adds a merged region of cells on a sheet.
  598. *
  599. * @param region to merge
  600. * @return index of this region
  601. * @throws IllegalArgumentException if region contains fewer than 2 cells
  602. * @throws IllegalStateException if region intersects with a multi-cell array formula
  603. * @throws IllegalStateException if region intersects with an existing region on this sheet
  604. */
  605. @Override
  606. public int addMergedRegion(CellRangeAddress region) {
  607. return addMergedRegion(region, true);
  608. }
  609. /**
  610. * Adds a merged region of cells (hence those cells form one).
  611. * Skips validation. It is possible to create overlapping merged regions
  612. * or create a merged region that intersects a multi-cell array formula
  613. * with this formula, which may result in a corrupt workbook.
  614. *
  615. * To check for merged regions overlapping array formulas or other merged regions
  616. * after addMergedRegionUnsafe has been called, call {@link #validateMergedRegions()}, which runs in O(n^2) time.
  617. *
  618. * @param region to merge
  619. * @return index of this region
  620. * @throws IllegalArgumentException if region contains fewer than 2 cells
  621. */
  622. @Override
  623. public int addMergedRegionUnsafe(CellRangeAddress region) {
  624. return addMergedRegion(region, false);
  625. }
  626. /**
  627. * Verify that merged regions do not intersect multi-cell array formulas and
  628. * no merged regions intersect another merged region in this sheet.
  629. *
  630. * @throws IllegalStateException if region intersects with a multi-cell array formula
  631. * @throws IllegalStateException if at least one region intersects with another merged region in this sheet
  632. */
  633. @Override
  634. public void validateMergedRegions() {
  635. checkForMergedRegionsIntersectingArrayFormulas();
  636. checkForIntersectingMergedRegions();
  637. }
  638. /**
  639. * adds a merged region of cells (hence those cells form one)
  640. *
  641. * @param region (rowfrom/colfrom-rowto/colto) to merge
  642. * @param validate whether to validate merged region
  643. * @return index of this region
  644. * @throws IllegalArgumentException if region contains fewer than 2 cells
  645. * @throws IllegalStateException if region intersects with an existing merged region
  646. * or multi-cell array formula on this sheet
  647. */
  648. private int addMergedRegion(CellRangeAddress region, boolean validate) {
  649. if (region.getNumberOfCells() < 2) {
  650. throw new IllegalArgumentException("Merged region " + region.formatAsString() + " must contain 2 or more cells");
  651. }
  652. region.validate(SpreadsheetVersion.EXCEL97);
  653. if (validate) {
  654. // throw IllegalStateException if the argument CellRangeAddress intersects with
  655. // a multi-cell array formula defined in this sheet
  656. validateArrayFormulas(region);
  657. // Throw IllegalStateException if the argument CellRangeAddress intersects with
  658. // a merged region already in this sheet
  659. validateMergedRegions(region);
  660. }
  661. return _sheet.addMergedRegion(region.getFirstRow(),
  662. region.getFirstColumn(),
  663. region.getLastRow(),
  664. region.getLastColumn());
  665. }
  666. private void validateArrayFormulas(CellRangeAddress region) {
  667. // FIXME: this may be faster if it looped over array formulas directly rather than looping over each cell in
  668. // the region and searching if that cell belongs to an array formula
  669. int firstRow = region.getFirstRow();
  670. int firstColumn = region.getFirstColumn();
  671. int lastRow = region.getLastRow();
  672. int lastColumn = region.getLastColumn();
  673. for (int rowIn = firstRow; rowIn <= lastRow; rowIn++) {
  674. HSSFRow row = getRow(rowIn);
  675. if (row == null) continue;
  676. for (int colIn = firstColumn; colIn <= lastColumn; colIn++) {
  677. HSSFCell cell = row.getCell(colIn);
  678. if (cell == null) continue;
  679. if (cell.isPartOfArrayFormulaGroup()) {
  680. CellRangeAddress arrayRange = cell.getArrayFormulaRange();
  681. if (arrayRange.getNumberOfCells() > 1 && region.intersects(arrayRange)) {
  682. String msg = "The range " + region.formatAsString() + " intersects with a multi-cell array formula. " +
  683. "You cannot merge cells of an array.";
  684. throw new IllegalStateException(msg);
  685. }
  686. }
  687. }
  688. }
  689. }
  690. /**
  691. * Verify that none of the merged regions intersect a multi-cell array formula in this sheet
  692. *
  693. * @throws IllegalStateException if candidate region intersects an existing array formula in this sheet
  694. */
  695. private void checkForMergedRegionsIntersectingArrayFormulas() {
  696. for (CellRangeAddress region : getMergedRegions()) {
  697. validateArrayFormulas(region);
  698. }
  699. }
  700. private void validateMergedRegions(CellRangeAddress candidateRegion) {
  701. for (final CellRangeAddress existingRegion : getMergedRegions()) {
  702. if (existingRegion.intersects(candidateRegion)) {
  703. throw new IllegalStateException("Cannot add merged region " + candidateRegion.formatAsString() +
  704. " to sheet because it overlaps with an existing merged region (" + existingRegion.formatAsString() + ").");
  705. }
  706. }
  707. }
  708. /**
  709. * Verify that no merged regions intersect another merged region in this sheet.
  710. *
  711. * @throws IllegalStateException if at least one region intersects with another merged region in this sheet
  712. */
  713. private void checkForIntersectingMergedRegions() {
  714. final List<CellRangeAddress> regions = getMergedRegions();
  715. final int size = regions.size();
  716. for (int i=0; i < size; i++) {
  717. final CellRangeAddress region = regions.get(i);
  718. for (final CellRangeAddress other : regions.subList(i+1, regions.size())) {
  719. if (region.intersects(other)) {
  720. String msg = "The range " + region.formatAsString() +
  721. " intersects with another merged region " +
  722. other.formatAsString() + " in this sheet";
  723. throw new IllegalStateException(msg);
  724. }
  725. }
  726. }
  727. }
  728. /**
  729. * Control if Excel should be asked to recalculate all formulas on this sheet
  730. * when the workbook is opened.<p>
  731. *
  732. * Calculating the formula values with {@link FormulaEvaluator} is the
  733. * recommended solution, but this may be used for certain cases where
  734. * evaluation in POI is not possible.<p>
  735. *
  736. * It is recommended to force recalcuation of formulas on workbook level using
  737. * {@link Workbook#setForceFormulaRecalculation(boolean)}
  738. * to ensure that all cross-worksheet formuals and external dependencies are updated.
  739. *
  740. * @param value true if the application will perform a full recalculation of
  741. * this worksheet values when the workbook is opened
  742. * @see Workbook#setForceFormulaRecalculation(boolean)
  743. */
  744. @Override
  745. public void setForceFormulaRecalculation(boolean value) {
  746. _sheet.setUncalced(value);
  747. }
  748. /**
  749. * Whether a record must be inserted or not at generation to indicate that
  750. * formula must be recalculated when workbook is opened.
  751. *
  752. * @return true if an uncalced record must be inserted or not at generation
  753. */
  754. @Override
  755. public boolean getForceFormulaRecalculation() {
  756. return _sheet.getUncalced();
  757. }
  758. /**
  759. * determines whether the output is vertically centered on the page.
  760. *
  761. * @param value true to vertically center, false otherwise.
  762. */
  763. @Override
  764. public void setVerticallyCenter(boolean value) {
  765. _sheet.getPageSettings().getVCenter().setVCenter(value);
  766. }
  767. /**
  768. * Determine whether printed output for this sheet will be vertically centered.
  769. */
  770. @Override
  771. public boolean getVerticallyCenter() {
  772. return _sheet.getPageSettings().getVCenter().getVCenter();
  773. }
  774. /**
  775. * determines whether the output is horizontally centered on the page.
  776. *
  777. * @param value true to horizontally center, false otherwise.
  778. */
  779. @Override
  780. public void setHorizontallyCenter(boolean value) {
  781. _sheet.getPageSettings().getHCenter().setHCenter(value);
  782. }
  783. /**
  784. * Determine whether printed output for this sheet will be horizontally centered.
  785. */
  786. @Override
  787. public boolean getHorizontallyCenter() {
  788. return _sheet.getPageSettings().getHCenter().getHCenter();
  789. }
  790. /**
  791. * Sets whether the worksheet is displayed from right to left instead of from left to right.
  792. *
  793. * @param value true for right to left, false otherwise.
  794. */
  795. @Override
  796. public void setRightToLeft(boolean value) {
  797. _sheet.getWindowTwo().setArabic(value);
  798. }
  799. /**
  800. * Whether the text is displayed in right-to-left mode in the window
  801. *
  802. * @return whether the text is displayed in right-to-left mode in the window
  803. */
  804. @Override
  805. public boolean isRightToLeft() {
  806. return _sheet.getWindowTwo().getArabic();
  807. }
  808. /**
  809. * removes a merged region of cells (hence letting them free)
  810. *
  811. * @param index of the region to unmerge
  812. */
  813. @Override
  814. public void removeMergedRegion(int index) {
  815. _sheet.removeMergedRegion(index);
  816. }
  817. /**
  818. * Removes a number of merged regions of cells (hence letting them free)
  819. *
  820. * @param indices A set of the regions to unmerge
  821. */
  822. @Override
  823. public void removeMergedRegions(Collection<Integer> indices) {
  824. for (int i : (new TreeSet<>(indices)).descendingSet()) {
  825. _sheet.removeMergedRegion(i);
  826. }
  827. }
  828. /**
  829. * returns the number of merged regions
  830. *
  831. * @return number of merged regions
  832. */
  833. @Override
  834. public int getNumMergedRegions() {
  835. return _sheet.getNumMergedRegions();
  836. }
  837. /**
  838. * @return the merged region at the specified index
  839. */
  840. @Override
  841. public CellRangeAddress getMergedRegion(int index) {
  842. return _sheet.getMergedRegionAt(index);
  843. }
  844. /**
  845. * @return the list of merged regions
  846. */
  847. @Override
  848. public List<CellRangeAddress> getMergedRegions() {
  849. List<CellRangeAddress> addresses = new ArrayList<>();
  850. int count = _sheet.getNumMergedRegions();
  851. for (int i=0; i < count; i++) {
  852. addresses.add(_sheet.getMergedRegionAt(i));
  853. }
  854. return addresses;
  855. }
  856. /**
  857. * @return an iterator of the PHYSICAL rows. Meaning the 3rd element may not
  858. * be the third row if say for instance the second row is undefined.
  859. * Call getRowNum() on each row if you care which one it is.
  860. */
  861. @Override
  862. public Iterator<Row> rowIterator() {
  863. @SuppressWarnings("unchecked") // can this clumsy generic syntax be improved?
  864. Iterator<Row> result = (Iterator<Row>) (Iterator<? extends Row>) _rows.values().iterator();
  865. return result;
  866. }
  867. /**
  868. * @return a spliterator of the PHYSICAL rows. Meaning the 3rd element may not
  869. * be the third row if say for instance the second row is undefined.
  870. * Call getRowNum() on each row if you care which one it is.
  871. *
  872. * @since POI 5.2.0
  873. */
  874. @Override
  875. @SuppressWarnings("unchecked") // can this clumsy generic syntax be improved?
  876. public Spliterator<Row> spliterator() {
  877. return (Spliterator<Row>)(Spliterator<? extends Row>) _rows.values().spliterator();
  878. }
  879. /**
  880. * used internally in the API to get the low level Sheet record represented by this
  881. * Object.
  882. *
  883. * @return Sheet - low level representation of this HSSFSheet.
  884. */
  885. @Internal
  886. public InternalSheet getSheet() {
  887. return _sheet;
  888. }
  889. /**
  890. * whether alternate expression evaluation is on
  891. *
  892. * @param b alternative expression evaluation or not
  893. */
  894. public void setAlternativeExpression(boolean b) {
  895. WSBoolRecord record =
  896. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  897. record.setAlternateExpression(b);
  898. }
  899. /**
  900. * whether alternative formula entry is on
  901. *
  902. * @param b alternative formulas or not
  903. */
  904. public void setAlternativeFormula(boolean b) {
  905. WSBoolRecord record =
  906. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  907. record.setAlternateFormula(b);
  908. }
  909. /**
  910. * show automatic page breaks or not
  911. *
  912. * @param b whether to show auto page breaks
  913. */
  914. @Override
  915. public void setAutobreaks(boolean b) {
  916. WSBoolRecord record =
  917. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  918. record.setAutobreaks(b);
  919. }
  920. /**
  921. * set whether sheet is a dialog sheet or not
  922. *
  923. * @param b isDialog or not
  924. */
  925. public void setDialog(boolean b) {
  926. WSBoolRecord record =
  927. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  928. record.setDialog(b);
  929. }
  930. /**
  931. * set whether to display the guts or not
  932. *
  933. * @param b guts or no guts (or glory)
  934. */
  935. @Override
  936. public void setDisplayGuts(boolean b) {
  937. WSBoolRecord record =
  938. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  939. record.setDisplayGuts(b);
  940. }
  941. /**
  942. * fit to page option is on
  943. *
  944. * @param b fit or not
  945. */
  946. @Override
  947. public void setFitToPage(boolean b) {
  948. WSBoolRecord record =
  949. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  950. record.setFitToPage(b);
  951. }
  952. /**
  953. * set if row summaries appear below detail in the outline
  954. *
  955. * @param b below or not
  956. */
  957. @Override
  958. public void setRowSumsBelow(boolean b) {
  959. WSBoolRecord record =
  960. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  961. record.setRowSumsBelow(b);
  962. //setAlternateExpression must be set in conjuction with setRowSumsBelow
  963. record.setAlternateExpression(b);
  964. }
  965. /**
  966. * set if col summaries appear right of the detail in the outline
  967. *
  968. * @param b right or not
  969. */
  970. @Override
  971. public void setRowSumsRight(boolean b) {
  972. WSBoolRecord record =
  973. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  974. record.setRowSumsRight(b);
  975. }
  976. /**
  977. * whether alternate expression evaluation is on
  978. *
  979. * @return alternative expression evaluation or not
  980. */
  981. public boolean getAlternateExpression() {
  982. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  983. .getAlternateExpression();
  984. }
  985. /**
  986. * whether alternative formula entry is on
  987. *
  988. * @return alternative formulas or not
  989. */
  990. public boolean getAlternateFormula() {
  991. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  992. .getAlternateFormula();
  993. }
  994. /**
  995. * show automatic page breaks or not
  996. *
  997. * @return whether to show auto page breaks
  998. */
  999. @Override
  1000. public boolean getAutobreaks() {
  1001. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  1002. .getAutobreaks();
  1003. }
  1004. /**
  1005. * get whether sheet is a dialog sheet or not
  1006. *
  1007. * @return isDialog or not
  1008. */
  1009. public boolean getDialog() {
  1010. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  1011. .getDialog();
  1012. }
  1013. /**
  1014. * get whether to display the guts or not
  1015. *
  1016. * @return guts or no guts (or glory)
  1017. */
  1018. @Override
  1019. public boolean getDisplayGuts() {
  1020. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  1021. .getDisplayGuts();
  1022. }
  1023. /**
  1024. * Gets the flag indicating whether the window should show 0 (zero) in cells containing zero value.
  1025. * When false, cells with zero value appear blank instead of showing the number zero.
  1026. * <p>
  1027. * In Excel 2003 this option can be changed in the Options dialog on the View tab.
  1028. * </p>
  1029. *
  1030. * @return whether all zero values on the worksheet are displayed
  1031. */
  1032. @Override
  1033. public boolean isDisplayZeros() {
  1034. return _sheet.getWindowTwo().getDisplayZeros();
  1035. }
  1036. /**
  1037. * Set whether the window should show 0 (zero) in cells containing zero value.
  1038. * When false, cells with zero value appear blank instead of showing the number zero.
  1039. * <p>
  1040. * In Excel 2003 this option can be set in the Options dialog on the View tab.
  1041. * </p>
  1042. *
  1043. * @param value whether to display or hide all zero values on the worksheet
  1044. */
  1045. @Override
  1046. public void setDisplayZeros(boolean value) {
  1047. _sheet.getWindowTwo().setDisplayZeros(value);
  1048. }
  1049. /**
  1050. * fit to page option is on
  1051. *
  1052. * @return fit or not
  1053. */
  1054. @Override
  1055. public boolean getFitToPage() {
  1056. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  1057. .getFitToPage();
  1058. }
  1059. /**
  1060. * get if row summaries appear below detail in the outline
  1061. *
  1062. * @return below or not
  1063. */
  1064. @Override
  1065. public boolean getRowSumsBelow() {
  1066. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  1067. .getRowSumsBelow();
  1068. }
  1069. /**
  1070. * get if col summaries appear right of the detail in the outline
  1071. *
  1072. * @return right or not
  1073. */
  1074. @Override
  1075. public boolean getRowSumsRight() {
  1076. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  1077. .getRowSumsRight();
  1078. }
  1079. /**
  1080. * Returns whether gridlines are printed.
  1081. *
  1082. * @return Gridlines are printed
  1083. */
  1084. @Override
  1085. public boolean isPrintGridlines() {
  1086. return getSheet().getPrintGridlines().getPrintGridlines();
  1087. }
  1088. /**
  1089. * Turns on or off the printing of gridlines.
  1090. *
  1091. * @param show boolean to turn on or off the printing of
  1092. * gridlines
  1093. */
  1094. @Override
  1095. public void setPrintGridlines(boolean show) {
  1096. getSheet().getPrintGridlines().setPrintGridlines(show);
  1097. }
  1098. /**
  1099. * Returns whether row and column headings are printed.
  1100. *
  1101. * @return row and column headings are printed
  1102. */
  1103. @Override
  1104. public boolean isPrintRowAndColumnHeadings() {
  1105. return getSheet().getPrintHeaders().getPrintHeaders();
  1106. }
  1107. /**
  1108. * Turns on or off the printing of row and column headings.
  1109. *
  1110. * @param show boolean to turn on or off the printing of
  1111. * row and column headings
  1112. */
  1113. @Override
  1114. public void setPrintRowAndColumnHeadings(boolean show) {
  1115. getSheet().getPrintHeaders().setPrintHeaders(show);
  1116. }
  1117. /**
  1118. * Gets the print setup object.
  1119. *
  1120. * @return The user model for the print setup object.
  1121. */
  1122. @Override
  1123. public HSSFPrintSetup getPrintSetup() {
  1124. return new HSSFPrintSetup(_sheet.getPageSettings().getPrintSetup());
  1125. }
  1126. @Override
  1127. public HSSFHeader getHeader() {
  1128. return new HSSFHeader(_sheet.getPageSettings());
  1129. }
  1130. @Override
  1131. public HSSFFooter getFooter() {
  1132. return new HSSFFooter(_sheet.getPageSettings());
  1133. }
  1134. /**
  1135. * Note - this is not the same as whether the sheet is focused (isActive)
  1136. *
  1137. * @return <code>true</code> if this sheet is currently selected
  1138. */
  1139. @Override
  1140. public boolean isSelected() {
  1141. return getSheet().getWindowTwo().getSelected();
  1142. }
  1143. /**
  1144. * Sets whether sheet is selected.
  1145. *
  1146. * @param sel Whether to select the sheet or deselect the sheet.
  1147. */
  1148. @Override
  1149. public void setSelected(boolean sel) {
  1150. getSheet().getWindowTwo().setSelected(sel);
  1151. }
  1152. /**
  1153. * @return <code>true</code> if this sheet is currently focused
  1154. */
  1155. public boolean isActive() {
  1156. return getSheet().getWindowTwo().isActive();
  1157. }
  1158. /**
  1159. * Sets whether sheet is selected.
  1160. *
  1161. * @param sel Whether to select the sheet or deselect the sheet.
  1162. */
  1163. public void setActive(boolean sel) {
  1164. getSheet().getWindowTwo().setActive(sel);
  1165. }
  1166. /**
  1167. * Gets the size of the margin in inches.
  1168. *
  1169. * @param margin which margin to get
  1170. * @return the size of the margin
  1171. */
  1172. @Override
  1173. public double getMargin(short margin) {
  1174. switch (margin) {
  1175. case FooterMargin:
  1176. return _sheet.getPageSettings().getPrintSetup().getFooterMargin();
  1177. case HeaderMargin:
  1178. return _sheet.getPageSettings().getPrintSetup().getHeaderMargin();
  1179. default:
  1180. return _sheet.getPageSettings().getMargin(margin);
  1181. }
  1182. }
  1183. /**
  1184. * Sets the size of the margin in inches.
  1185. *
  1186. * @param margin which margin to get
  1187. * @param size the size of the margin
  1188. */
  1189. @Override
  1190. public void setMargin(short margin, double size) {
  1191. switch (margin) {
  1192. case FooterMargin:
  1193. _sheet.getPageSettings().getPrintSetup().setFooterMargin(size);
  1194. break;
  1195. case HeaderMargin:
  1196. _sheet.getPageSettings().getPrintSetup().setHeaderMargin(size);
  1197. break;
  1198. default:
  1199. _sheet.getPageSettings().setMargin(margin, size);
  1200. }
  1201. }
  1202. private WorksheetProtectionBlock getProtectionBlock() {
  1203. return _sheet.getProtectionBlock();
  1204. }
  1205. /**
  1206. * Answer whether protection is enabled or disabled
  1207. *
  1208. * @return true =&gt; protection enabled; false =&gt; protection disabled
  1209. */
  1210. @Override
  1211. public boolean getProtect() {
  1212. return getProtectionBlock().isSheetProtected();
  1213. }
  1214. /**
  1215. * @return hashed password
  1216. */
  1217. public short getPassword() {
  1218. return (short) getProtectionBlock().getPasswordHash();
  1219. }
  1220. /**
  1221. * Answer whether object protection is enabled or disabled
  1222. *
  1223. * @return true =&gt; protection enabled; false =&gt; protection disabled
  1224. */
  1225. public boolean getObjectProtect() {
  1226. return getProtectionBlock().isObjectProtected();
  1227. }
  1228. /**
  1229. * Answer whether scenario protection is enabled or disabled
  1230. *
  1231. * @return true =&gt; protection enabled; false =&gt; protection disabled
  1232. */
  1233. @Override
  1234. public boolean getScenarioProtect() {
  1235. return getProtectionBlock().isScenarioProtected();
  1236. }
  1237. /**
  1238. * Sets the protection enabled as well as the password
  1239. *
  1240. * @param password to set for protection. Pass <code>null</code> to remove protection
  1241. */
  1242. @Override
  1243. public void protectSheet(String password) {
  1244. getProtectionBlock().protectSheet(password, true, true); //protect objs&scenarios(normal)
  1245. }
  1246. /**
  1247. * Sets the zoom magnification for the sheet. The zoom is expressed as a
  1248. * fraction. For example to express a zoom of 75% use 3 for the numerator
  1249. * and 4 for the denominator.
  1250. *
  1251. * @param numerator The numerator for the zoom magnification.
  1252. * @param denominator The denominator for the zoom magnification.
  1253. * @see #setZoom(int)
  1254. */
  1255. public void setZoom(int numerator, int denominator) {
  1256. if (numerator < 1 || numerator > 65535)
  1257. throw new IllegalArgumentException("Numerator must be greater than 0 and less than 65536");
  1258. if (denominator < 1 || denominator > 65535)
  1259. throw new IllegalArgumentException("Denominator must be greater than 0 and less than 65536");
  1260. SCLRecord sclRecord = new SCLRecord();
  1261. sclRecord.setNumerator((short) numerator);
  1262. sclRecord.setDenominator((short) denominator);
  1263. getSheet().setSCLRecord(sclRecord);
  1264. }
  1265. /**
  1266. * Window zoom magnification for current view representing percent values.
  1267. * Valid values range from 10 to 400. Horizontal &amp; Vertical scale together.
  1268. *
  1269. * For example:
  1270. * <pre>
  1271. * 10 - 10%
  1272. * 20 - 20%
  1273. * ...
  1274. * 100 - 100%
  1275. * ...
  1276. * 400 - 400%
  1277. * </pre>
  1278. *
  1279. * @param scale window zoom magnification
  1280. * @throws IllegalArgumentException if scale is invalid
  1281. */
  1282. @Override
  1283. public void setZoom(int scale) {
  1284. setZoom(scale, 100);
  1285. }
  1286. /**
  1287. * The top row in the visible view when the sheet is
  1288. * first viewed after opening it in a viewer
  1289. *
  1290. * @return short indicating the rownum (0 based) of the top row
  1291. */
  1292. @Override
  1293. public short getTopRow() {
  1294. return _sheet.getTopRow();
  1295. }
  1296. /**
  1297. * The left col in the visible view when the sheet is
  1298. * first viewed after opening it in a viewer
  1299. *
  1300. * @return short indicating the rownum (0 based) of the top row
  1301. */
  1302. @Override
  1303. public short getLeftCol() {
  1304. return _sheet.getLeftCol();
  1305. }
  1306. /**
  1307. * Sets desktop window pane display area, when the
  1308. * file is first opened in a viewer.
  1309. *
  1310. * @param topRow the top row to show in desktop window pane
  1311. * @param leftCol the left column to show in desktop window pane
  1312. */
  1313. @Override
  1314. public void showInPane(int topRow, int leftCol) {
  1315. int maxrow = SpreadsheetVersion.EXCEL97.getLastRowIndex();
  1316. if (topRow > maxrow) throw new IllegalArgumentException("Maximum row number is " + maxrow);
  1317. showInPane((short) topRow, (short) leftCol);
  1318. }
  1319. /**
  1320. * Sets desktop window pane display area, when the
  1321. * file is first opened in a viewer.
  1322. *
  1323. * @param toprow the top row to show in desktop window pane
  1324. * @param leftcol the left column to show in desktop window pane
  1325. */
  1326. private void showInPane(short toprow, short leftcol) {
  1327. _sheet.setTopRow(toprow);
  1328. _sheet.setLeftCol(leftcol);
  1329. }
  1330. /**
  1331. * Shifts, grows, or shrinks the merged regions due to a row shift
  1332. *
  1333. * @param startRow the start-index of the rows to shift, zero-based
  1334. * @param endRow the end-index of the rows to shift, zero-based
  1335. * @param n how far to shift, negative to shift up
  1336. * @param isRow unused, kept for backwards compatibility
  1337. * @deprecated POI 3.15 beta 2. Use {@link HSSFRowShifter#shiftMergedRegions(int, int, int)}.
  1338. */
  1339. protected void shiftMerged(int startRow, int endRow, int n, boolean isRow) {
  1340. RowShifter rowShifter = new HSSFRowShifter(this);
  1341. rowShifter.shiftMergedRegions(startRow, endRow, n);
  1342. }
  1343. /**
  1344. * Shifts rows between startRow and endRow n number of rows.
  1345. * If you use a negative number, it will shift rows up.
  1346. * Code ensures that rows don't wrap around.<p>
  1347. *
  1348. * Calls {@code shiftRows(startRow, endRow, n, false, false);}<p>
  1349. *
  1350. * Additionally shifts merged regions that are completely defined in these
  1351. * rows (ie. merged 2 cells on a row to be shifted).
  1352. *
  1353. * @param startRow the row to start shifting
  1354. * @param endRow the row to end shifting
  1355. * @param n the number of rows to shift
  1356. */
  1357. @Override
  1358. public void shiftRows(int startRow, int endRow, int n) {
  1359. shiftRows(startRow, endRow, n, false, false);
  1360. }
  1361. /**
  1362. * Shifts rows between startRow and endRow n number of rows.
  1363. * If you use a negative number, it will shift rows up.
  1364. * Code ensures that rows don't wrap around<p>
  1365. *
  1366. * Additionally shifts merged regions that are completely defined in these
  1367. * rows (ie. merged 2 cells on a row to be shifted). All merged regions that are
  1368. * completely overlaid by shifting will be deleted.<p>
  1369. *
  1370. * TODO Might want to add bounds checking here
  1371. *
  1372. * @param startRow the row to start shifting
  1373. * @param endRow the row to end shifting
  1374. * @param n the number of rows to shift
  1375. * @param copyRowHeight whether to copy the row height during the shift
  1376. * @param resetOriginalRowHeight whether to set the original row's height to the default
  1377. */
  1378. @Override
  1379. public void shiftRows(int startRow, int endRow, int n, boolean copyRowHeight, boolean resetOriginalRowHeight) {
  1380. shiftRows(startRow, endRow, n, copyRowHeight, resetOriginalRowHeight, true);
  1381. }
  1382. /**
  1383. * bound a row number between 0 and last row index (65535)
  1384. *
  1385. * @param row the row number
  1386. */
  1387. private static int clip(int row) {
  1388. return Math.min(
  1389. Math.max(0, row),
  1390. SpreadsheetVersion.EXCEL97.getLastRowIndex());
  1391. }
  1392. /**
  1393. * Shifts rows between startRow and endRow n number of rows.
  1394. * If you use a negative number, it will shift rows up.
  1395. * Code ensures that rows don't wrap around<p>
  1396. *
  1397. * Additionally shifts merged regions that are completely defined in these
  1398. * rows (ie. merged 2 cells on a row to be shifted).<p>
  1399. *
  1400. * TODO Might want to add bounds checking here
  1401. *
  1402. * @param startRow the row to start shifting
  1403. * @param endRow the row to end shifting
  1404. * @param n the number of rows to shift
  1405. * @param copyRowHeight whether to copy the row height during the shift
  1406. * @param resetOriginalRowHeight whether to set the original row's height to the default
  1407. * @param moveComments whether to move comments at the same time as the cells they are attached to
  1408. */
  1409. public void shiftRows(int startRow, int endRow, int n,
  1410. boolean copyRowHeight, boolean resetOriginalRowHeight, boolean moveComments) {
  1411. int s, inc;
  1412. if (endRow < startRow) {
  1413. throw new IllegalArgumentException("startRow must be less than or equal to endRow. To shift rows up, use n<0.");
  1414. }
  1415. if (n < 0) {
  1416. s = startRow;
  1417. inc = 1;
  1418. } else if (n > 0) {
  1419. s = endRow;
  1420. inc = -1;
  1421. } else {
  1422. // Nothing to do
  1423. return;
  1424. }
  1425. final RowShifter rowShifter = new HSSFRowShifter(this);
  1426. // Move comments from the source row to the
  1427. // destination row. Note that comments can
  1428. // exist for cells which are null
  1429. // If the row shift would shift the comments off the sheet
  1430. // (above the first row or below the last row), this code will shift the
  1431. // comments to the first or last row, rather than moving them out of
  1432. // bounds or deleting them
  1433. if (moveComments) {
  1434. moveCommentsForRowShift(startRow, endRow, n);
  1435. }
  1436. // Shift Merged Regions
  1437. rowShifter.shiftMergedRegions(startRow, endRow, n);
  1438. // Shift Row Breaks
  1439. _sheet.getPageSettings().shiftRowBreaks(startRow, endRow, n);
  1440. // Delete overwritten hyperlinks
  1441. deleteOverwrittenHyperlinksForRowShift(startRow, endRow, n);
  1442. for (int rowNum = s; rowNum >= startRow && rowNum <= endRow && rowNum >= 0 && rowNum < 65536; rowNum += inc) {
  1443. HSSFRow row = getRow(rowNum);
  1444. // notify all cells in this row that we are going to shift them,
  1445. // it can throw IllegalStateException if the operation is not allowed, for example,
  1446. // if the row contains cells included in a multi-cell array formula
  1447. if (row != null) notifyRowShifting(row);
  1448. HSSFRow row2Replace = getRow(rowNum + n);
  1449. if (row2Replace == null)
  1450. row2Replace = createRow(rowNum + n);
  1451. // Remove all the old cells from the row we'll
  1452. // be writing to, before we start overwriting
  1453. // any cells. This avoids issues with cells
  1454. // changing type, and records not being correctly
  1455. // overwritten
  1456. row2Replace.removeAllCells();
  1457. // If this row doesn't exist, nothing needs to
  1458. // be done for the now empty destination row
  1459. if (row == null) continue; // Nothing to do for this row
  1460. // Fix up row heights if required
  1461. if (copyRowHeight) {
  1462. row2Replace.setHeight(row.getHeight());
  1463. }
  1464. if (resetOriginalRowHeight) {
  1465. row.setHeight((short) 0xff);
  1466. }
  1467. // Copy each cell from the source row to
  1468. // the destination row
  1469. for (Iterator<Cell> cells = row.cellIterator(); cells.hasNext(); ) {
  1470. HSSFCell cell = (HSSFCell) cells.next();
  1471. HSSFHyperlink link = cell.getHyperlink();
  1472. row.removeCell(cell);
  1473. CellValueRecordInterface cellRecord = cell.getCellValueRecord();
  1474. cellRecord.setRow(rowNum + n);
  1475. row2Replace.createCellFromRecord(cellRecord);
  1476. _sheet.addValueRecord(rowNum + n, cellRecord);
  1477. if (link != null) {
  1478. link.setFirstRow(link.getFirstRow() + n);
  1479. link.setLastRow(link.getLastRow() + n);
  1480. }
  1481. }
  1482. // Now zap all the cells in the source row
  1483. row.removeAllCells();
  1484. }
  1485. // Re-compute the first and last rows of the sheet as needed
  1486. recomputeFirstAndLastRowsForRowShift(startRow, endRow, n);
  1487. int sheetIndex = _workbook.getSheetIndex(this);
  1488. short externSheetIndex = _book.checkExternSheet(sheetIndex);
  1489. String sheetName = _workbook.getSheetName(sheetIndex);
  1490. FormulaShifter formulaShifter = FormulaShifter.createForRowShift(
  1491. externSheetIndex, sheetName, startRow, endRow, n, SpreadsheetVersion.EXCEL97);
  1492. // Update formulas that refer to rows that have been moved
  1493. updateFormulasForShift(formulaShifter);
  1494. }
  1495. private void updateFormulasForShift(FormulaShifter formulaShifter) {
  1496. int sheetIndex = _workbook.getSheetIndex(this);
  1497. short externSheetIndex = _book.checkExternSheet(sheetIndex);
  1498. // update formulas on this sheet that point to rows which have been moved
  1499. _sheet.updateFormulasAfterCellShift(formulaShifter, externSheetIndex);
  1500. // update formulas on other sheets that point to rows that have been moved on this sheet
  1501. int nSheets = _workbook.getNumberOfSheets();
  1502. for (int i = 0; i < nSheets; i++) {
  1503. InternalSheet otherSheet = _workbook.getSheetAt(i).getSheet();
  1504. if (otherSheet == this._sheet) {
  1505. continue;
  1506. }
  1507. short otherExtSheetIx = _book.checkExternSheet(i);
  1508. otherSheet.updateFormulasAfterCellShift(formulaShifter, otherExtSheetIx);
  1509. }
  1510. _workbook.getWorkbook().updateNamesAfterCellShift(formulaShifter);
  1511. }
  1512. private void recomputeFirstAndLastRowsForRowShift(int startRow, int endRow, int n) {
  1513. if (n > 0) {
  1514. // Rows are moving down
  1515. if (startRow == _firstrow) {
  1516. // Need to walk forward to find the first non-blank row
  1517. _firstrow = Math.max(startRow + n, 0);
  1518. for (int i = startRow + 1; i < startRow + n; i++) {
  1519. if (getRow(i) != null) {
  1520. _firstrow = i;
  1521. break;
  1522. }
  1523. }
  1524. }
  1525. if (endRow + n > _lastrow) {
  1526. _lastrow = Math.min(endRow + n, SpreadsheetVersion.EXCEL97.getLastRowIndex());
  1527. }
  1528. } else {
  1529. // Rows are moving up
  1530. if (startRow + n < _firstrow) {
  1531. _firstrow = Math.max(startRow + n, 0);
  1532. }
  1533. if (endRow == _lastrow) {
  1534. // Need to walk backward to find the last non-blank row
  1535. // NOTE: n is always negative here
  1536. _lastrow = Math.min(endRow + n, SpreadsheetVersion.EXCEL97.getLastRowIndex());
  1537. for (int i = endRow - 1; i > endRow + n; i--) {
  1538. if (getRow(i) != null) {
  1539. _lastrow = i;
  1540. break;
  1541. }
  1542. }
  1543. }
  1544. }
  1545. }
  1546. private void deleteOverwrittenHyperlinksForRowShift(int startRow, int endRow, int n) {
  1547. final int firstOverwrittenRow = startRow + n;
  1548. final int lastOverwrittenRow = endRow + n;
  1549. for (HSSFHyperlink link : getHyperlinkList()) {
  1550. // If hyperlink is fully contained in the rows that will be overwritten, delete the hyperlink
  1551. final int firstRow = link.getFirstRow();
  1552. final int lastRow = link.getLastRow();
  1553. if (firstOverwrittenRow <= firstRow
  1554. && firstRow <= lastOverwrittenRow
  1555. && lastOverwrittenRow <= lastRow
  1556. && lastRow <= lastOverwrittenRow) {
  1557. removeHyperlink(link);
  1558. }
  1559. }
  1560. }
  1561. private void moveCommentsForRowShift(int startRow, int endRow, int n) {
  1562. final HSSFPatriarch patriarch = createDrawingPatriarch();
  1563. for (final HSSFShape shape : patriarch.getChildren()) {
  1564. if (!(shape instanceof HSSFComment)) {
  1565. continue;
  1566. }
  1567. final HSSFComment comment = (HSSFComment) shape;
  1568. final int r = comment.getRow();
  1569. if (startRow <= r && r <= endRow) {
  1570. comment.setRow(clip(r + n));
  1571. }
  1572. }
  1573. }
  1574. /**
  1575. * Shifts columns in range [startColumn, endColumn] for n places to the right.
  1576. * For n &lt; 0, it will shift columns left.
  1577. * Additionally adjusts formulas.
  1578. * Probably should also process other features (hyperlinks, comments...) in the way analog to shiftRows method
  1579. * @param startColumn the column to start shifting
  1580. * @param endColumn the column to end shifting
  1581. * @param n the number of columns to shift
  1582. */
  1583. @Beta
  1584. @Override
  1585. public void shiftColumns(int startColumn, int endColumn, int n){
  1586. HSSFColumnShifter columnShifter = new HSSFColumnShifter(this);
  1587. columnShifter.shiftColumns(startColumn, endColumn, n);
  1588. int sheetIndex = _workbook.getSheetIndex(this);
  1589. short externSheetIndex = _book.checkExternSheet(sheetIndex);
  1590. String sheetName = _workbook.getSheetName(sheetIndex);
  1591. FormulaShifter formulaShifter = FormulaShifter.createForColumnShift(
  1592. externSheetIndex, sheetName, startColumn, endColumn, n, SpreadsheetVersion.EXCEL97);
  1593. updateFormulasForShift(formulaShifter);
  1594. // add logic for hyperlinks etc, like in shiftRows()
  1595. }
  1596. protected void insertChartRecords(List<Record> records) {
  1597. int window2Loc = _sheet.findFirstRecordLocBySid(WindowTwoRecord.sid);
  1598. _sheet.getRecords().addAll(window2Loc, records);
  1599. }
  1600. private void notifyRowShifting(HSSFRow row) {
  1601. String msg = "Row[rownum=" + row.getRowNum() + "] contains cell(s) included in a multi-cell array formula. " +
  1602. "You cannot change part of an array.";
  1603. for (Cell cell : row) {
  1604. HSSFCell hcell = (HSSFCell) cell;
  1605. if (hcell.isPartOfArrayFormulaGroup()) {
  1606. hcell.tryToDeleteArrayFormula(msg);
  1607. }
  1608. }
  1609. }
  1610. /**
  1611. * Creates a split (freezepane). Any existing freezepane or split pane is overwritten.<p>
  1612. *
  1613. * If both colSplit and rowSplit are zero then the existing freeze pane is removed
  1614. *
  1615. * @param colSplit Horizonatal position of split.
  1616. * @param rowSplit Vertical position of split.
  1617. * @param leftmostColumn Left column visible in right pane.
  1618. * @param topRow Top row visible in bottom pane
  1619. */
  1620. @Override
  1621. public void createFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow) {
  1622. validateColumn(colSplit);
  1623. validateRow(rowSplit);
  1624. if (leftmostColumn < colSplit)
  1625. throw new IllegalArgumentException("leftmostColumn parameter must not be less than colSplit parameter");
  1626. if (topRow < rowSplit)
  1627. throw new IllegalArgumentException("topRow parameter must not be less than leftmostColumn parameter");
  1628. getSheet().createFreezePane(colSplit, rowSplit, topRow, leftmostColumn);
  1629. }
  1630. /**
  1631. * Creates a split (freezepane). Any existing freezepane or split pane is overwritten.<p>
  1632. *
  1633. * If both colSplit and rowSplit are zero then the existing freeze pane is removed
  1634. *
  1635. * @param colSplit Horizonatal position of split.
  1636. * @param rowSplit Vertical position of split.
  1637. */
  1638. @Override
  1639. public void createFreezePane(int colSplit, int rowSplit) {
  1640. createFreezePane(colSplit, rowSplit, colSplit, rowSplit);
  1641. }
  1642. /**
  1643. * Creates a split pane. Any existing freezepane or split pane is overwritten.
  1644. *
  1645. * @param xSplitPos Horizonatal position of split (in 1/20th of a point).
  1646. * @param ySplitPos Vertical position of split (in 1/20th of a point).
  1647. * @param topRow Top row visible in bottom pane
  1648. * @param leftmostColumn Left column visible in right pane.
  1649. * @param activePane Active pane. One of: PANE_LOWER_RIGHT,
  1650. * PANE_UPPER_RIGHT, PANE_LOWER_LEFT, PANE_UPPER_LEFT
  1651. * @see #PANE_LOWER_LEFT
  1652. * @see #PANE_LOWER_RIGHT
  1653. * @see #PANE_UPPER_LEFT
  1654. * @see #PANE_UPPER_RIGHT
  1655. */
  1656. @Override
  1657. public void createSplitPane(int xSplitPos, int ySplitPos, int leftmostColumn, int topRow, int activePane) {
  1658. getSheet().createSplitPane(xSplitPos, ySplitPos, topRow, leftmostColumn, activePane);
  1659. }
  1660. /**
  1661. * Returns the information regarding the currently configured pane (split or freeze).
  1662. *
  1663. * @return null if no pane configured, or the pane information.
  1664. */
  1665. @Override
  1666. public PaneInformation getPaneInformation() {
  1667. return getSheet().getPaneInformation();
  1668. }
  1669. /**
  1670. * Sets whether the gridlines are shown in a viewer.
  1671. *
  1672. * @param show whether to show gridlines or not
  1673. */
  1674. @Override
  1675. public void setDisplayGridlines(boolean show) {
  1676. _sheet.setDisplayGridlines(show);
  1677. }
  1678. /**
  1679. * Returns if gridlines are displayed.
  1680. *
  1681. * @return whether gridlines are displayed
  1682. */
  1683. @Override
  1684. public boolean isDisplayGridlines() {
  1685. return _sheet.isDisplayGridlines();
  1686. }
  1687. /**
  1688. * Sets whether the formulas are shown in a viewer.
  1689. *
  1690. * @param show whether to show formulas or not
  1691. */
  1692. @Override
  1693. public void setDisplayFormulas(boolean show) {
  1694. _sheet.setDisplayFormulas(show);
  1695. }
  1696. /**
  1697. * Returns if formulas are displayed.
  1698. *
  1699. * @return whether formulas are displayed
  1700. */
  1701. @Override
  1702. public boolean isDisplayFormulas() {
  1703. return _sheet.isDisplayFormulas();
  1704. }
  1705. /**
  1706. * Sets whether the RowColHeadings are shown in a viewer.
  1707. *
  1708. * @param show whether to show RowColHeadings or not
  1709. */
  1710. @Override
  1711. public void setDisplayRowColHeadings(boolean show) {
  1712. _sheet.setDisplayRowColHeadings(show);
  1713. }
  1714. /**
  1715. * Returns if RowColHeadings are displayed.
  1716. *
  1717. * @return whether RowColHeadings are displayed
  1718. */
  1719. @Override
  1720. public boolean isDisplayRowColHeadings() {
  1721. return _sheet.isDisplayRowColHeadings();
  1722. }
  1723. /**
  1724. * Sets a page break at the indicated row
  1725. * Breaks occur above the specified row and left of the specified column inclusive.<p>
  1726. *
  1727. * For example, <code>sheet.setColumnBreak(2);</code> breaks the sheet into two parts
  1728. * with columns A,B,C in the first and D,E,... in the second. Simuilar, <code>sheet.setRowBreak(2);</code>
  1729. * breaks the sheet into two parts with first three rows (rownum=1...3) in the first part
  1730. * and rows starting with rownum=4 in the second.
  1731. *
  1732. * @param row the row to break, inclusive
  1733. */
  1734. @Override
  1735. public void setRowBreak(int row) {
  1736. validateRow(row);
  1737. _sheet.getPageSettings().setRowBreak(row, (short) 0, (short) 255);
  1738. }
  1739. /**
  1740. * @return <code>true</code> if there is a page break at the indicated row
  1741. */
  1742. @Override
  1743. public boolean isRowBroken(int row) {
  1744. return _sheet.getPageSettings().isRowBroken(row);
  1745. }
  1746. /**
  1747. * Removes the page break at the indicated row
  1748. */
  1749. @Override
  1750. public void removeRowBreak(int row) {
  1751. _sheet.getPageSettings().removeRowBreak(row);
  1752. }
  1753. /**
  1754. * @return row indexes of all the horizontal page breaks, never <code>null</code>
  1755. */
  1756. @Override
  1757. public int[] getRowBreaks() {
  1758. //we can probably cache this information, but this should be a sparsely used function
  1759. return _sheet.getPageSettings().getRowBreaks();
  1760. }
  1761. /**
  1762. * @return column indexes of all the vertical page breaks, never <code>null</code>
  1763. */
  1764. @Override
  1765. public int[] getColumnBreaks() {
  1766. //we can probably cache this information, but this should be a sparsely used function
  1767. return _sheet.getPageSettings().getColumnBreaks();
  1768. }
  1769. /**
  1770. * Sets a page break at the indicated column.
  1771. * Breaks occur above the specified row and left of the specified column inclusive.<p>
  1772. *
  1773. * For example, <code>sheet.setColumnBreak(2);</code> breaks the sheet into two parts
  1774. * with columns A,B,C in the first and D,E,... in the second. Simuilar, {@code sheet.setRowBreak(2);}
  1775. * breaks the sheet into two parts with first three rows (rownum=1...3) in the first part
  1776. * and rows starting with rownum=4 in the second.
  1777. *
  1778. * @param column the column to break, inclusive
  1779. */
  1780. @Override
  1781. public void setColumnBreak(int column) {
  1782. validateColumn((short) column);
  1783. _sheet.getPageSettings().setColumnBreak((short) column, (short) 0, (short) SpreadsheetVersion.EXCEL97.getLastRowIndex());
  1784. }
  1785. /**
  1786. * Determines if there is a page break at the indicated column
  1787. *
  1788. * @param column FIXME: Document this!
  1789. * @return FIXME: Document this!
  1790. */
  1791. @Override
  1792. public boolean isColumnBroken(int column) {
  1793. return _sheet.getPageSettings().isColumnBroken(column);
  1794. }
  1795. /**
  1796. * Removes a page break at the indicated column
  1797. *
  1798. * @param column The index of the column for which to remove a page-break, zero-based
  1799. */
  1800. @Override
  1801. public void removeColumnBreak(int column) {
  1802. _sheet.getPageSettings().removeColumnBreak(column);
  1803. }
  1804. /**
  1805. * Runs a bounds check for row numbers
  1806. *
  1807. * @param row the index of the row to validate, zero-based
  1808. */
  1809. protected void validateRow(int row) {
  1810. int maxrow = SpreadsheetVersion.EXCEL97.getLastRowIndex();
  1811. if (row > maxrow) throw new IllegalArgumentException("Maximum row number is " + maxrow);
  1812. if (row < 0) throw new IllegalArgumentException("Minumum row number is 0");
  1813. }
  1814. /**
  1815. * Runs a bounds check for column numbers
  1816. *
  1817. * @param column the index of the column to validate, zero-based
  1818. */
  1819. protected void validateColumn(int column) {
  1820. int maxcol = SpreadsheetVersion.EXCEL97.getLastColumnIndex();
  1821. if (column > maxcol) throw new IllegalArgumentException("Maximum column number is " + maxcol);
  1822. if (column < 0) throw new IllegalArgumentException("Minimum column number is 0");
  1823. }
  1824. /**
  1825. * Aggregates the drawing records and dumps the escher record hierarchy
  1826. * to the standard output.
  1827. */
  1828. public void dumpDrawingRecords(boolean fat, PrintWriter pw) {
  1829. _sheet.aggregateDrawingRecords(_book.getDrawingManager(), false);
  1830. EscherAggregate r = (EscherAggregate) getSheet().findFirstRecordBySid(EscherAggregate.sid);
  1831. List<EscherRecord> escherRecords = r.getEscherRecords();
  1832. for (EscherRecord escherRecord : escherRecords) {
  1833. if (fat) {
  1834. pw.println(escherRecord);
  1835. } else {
  1836. escherRecord.display(pw, 0);
  1837. }
  1838. }
  1839. pw.flush();
  1840. }
  1841. /**
  1842. * Returns the agregate escher records for this sheet,
  1843. * it there is one.
  1844. */
  1845. public EscherAggregate getDrawingEscherAggregate() {
  1846. _book.findDrawingGroup();
  1847. // If there's now no drawing manager, then there's
  1848. // no drawing escher records on the workbook
  1849. if (_book.getDrawingManager() == null) {
  1850. return null;
  1851. }
  1852. int found = _sheet.aggregateDrawingRecords(
  1853. _book.getDrawingManager(), false
  1854. );
  1855. if (found == -1) {
  1856. // Workbook has drawing stuff, but this sheet doesn't
  1857. return null;
  1858. }
  1859. // Grab our aggregate record, and wire it up
  1860. return (EscherAggregate) _sheet.findFirstRecordBySid(EscherAggregate.sid);
  1861. }
  1862. /**
  1863. * This will hold any graphics or charts for the sheet.
  1864. *
  1865. * @return the top-level drawing patriarch, if there is one, else returns null
  1866. */
  1867. @Override
  1868. public HSSFPatriarch getDrawingPatriarch() {
  1869. _patriarch = getPatriarch(false);
  1870. return _patriarch;
  1871. }
  1872. /**
  1873. * Creates the top-level drawing patriarch.
  1874. * <p>This may then be used to add graphics or charts.</p>
  1875. * <p>Note that this will normally have the effect of removing
  1876. * any existing drawings on this sheet.</p>
  1877. *
  1878. * @return The new patriarch.
  1879. */
  1880. @Override
  1881. public HSSFPatriarch createDrawingPatriarch() {
  1882. _patriarch = getPatriarch(true);
  1883. return _patriarch;
  1884. }
  1885. private HSSFPatriarch getPatriarch(boolean createIfMissing) {
  1886. if (_patriarch != null) {
  1887. return _patriarch;
  1888. }
  1889. DrawingManager2 dm = _book.findDrawingGroup();
  1890. if (null == dm) {
  1891. if (!createIfMissing) {
  1892. return null;
  1893. } else {
  1894. _book.createDrawingGroup();
  1895. dm = _book.getDrawingManager();
  1896. }
  1897. }
  1898. EscherAggregate agg = (EscherAggregate) _sheet.findFirstRecordBySid(EscherAggregate.sid);
  1899. if (null == agg) {
  1900. int pos = _sheet.aggregateDrawingRecords(dm, false);
  1901. if (-1 == pos) {
  1902. if (createIfMissing) {
  1903. pos = _sheet.aggregateDrawingRecords(dm, true);
  1904. agg = (EscherAggregate) _sheet.getRecords().get(pos);
  1905. HSSFPatriarch patriarch = new HSSFPatriarch(this, agg);
  1906. patriarch.afterCreate();
  1907. return patriarch;
  1908. } else {
  1909. return null;
  1910. }
  1911. }
  1912. agg = (EscherAggregate) _sheet.getRecords().get(pos);
  1913. }
  1914. return new HSSFPatriarch(this, agg);
  1915. }
  1916. /**
  1917. * Expands or collapses a column group.
  1918. *
  1919. * @param columnNumber One of the columns in the group.
  1920. * @param collapsed true = collapse group, false = expand group.
  1921. */
  1922. @Override
  1923. public void setColumnGroupCollapsed(int columnNumber, boolean collapsed) {
  1924. _sheet.setColumnGroupCollapsed(columnNumber, collapsed);
  1925. }
  1926. /**
  1927. * Create an outline for the provided column range.
  1928. *
  1929. * @param fromColumn beginning of the column range.
  1930. * @param toColumn end of the column range.
  1931. */
  1932. @Override
  1933. public void groupColumn(int fromColumn, int toColumn) {
  1934. _sheet.groupColumnRange(fromColumn, toColumn, true);
  1935. }
  1936. @Override
  1937. public void ungroupColumn(int fromColumn, int toColumn) {
  1938. _sheet.groupColumnRange(fromColumn, toColumn, false);
  1939. }
  1940. /**
  1941. * Tie a range of cell together so that they can be collapsed or expanded
  1942. *
  1943. * @param fromRow start row (0-based)
  1944. * @param toRow end row (0-based)
  1945. */
  1946. @Override
  1947. public void groupRow(int fromRow, int toRow) {
  1948. _sheet.groupRowRange(fromRow, toRow, true);
  1949. }
  1950. @Override
  1951. public void ungroupRow(int fromRow, int toRow) {
  1952. _sheet.groupRowRange(fromRow, toRow, false);
  1953. }
  1954. @Override
  1955. public void setRowGroupCollapsed(int rowIndex, boolean collapse) {
  1956. if (collapse) {
  1957. _sheet.getRowsAggregate().collapseRow(rowIndex);
  1958. } else {
  1959. _sheet.getRowsAggregate().expandRow(rowIndex);
  1960. }
  1961. }
  1962. /**
  1963. * Sets the default column style for a given column. POI will only apply this style to new cells added to the sheet.
  1964. *
  1965. * @param column the column index
  1966. * @param style the style to set
  1967. */
  1968. @Override
  1969. public void setDefaultColumnStyle(int column, CellStyle style) {
  1970. _sheet.setDefaultColumnStyle(column, style.getIndex());
  1971. }
  1972. /**
  1973. * Adjusts the column width to fit the contents.<p>
  1974. *
  1975. * This process can be relatively slow on large sheets, so this should
  1976. * normally only be called once per column, at the end of your
  1977. * processing.
  1978. *
  1979. * @param column the column index
  1980. */
  1981. @Override
  1982. public void autoSizeColumn(int column) {
  1983. autoSizeColumn(column, false);
  1984. }
  1985. /**
  1986. * Adjusts the column width to fit the contents.<p>
  1987. *
  1988. * This process can be relatively slow on large sheets, so this should
  1989. * normally only be called once per column, at the end of your
  1990. * processing.<p>
  1991. *
  1992. * You can specify whether the content of merged cells should be considered or ignored.
  1993. * Default is to ignore merged cells.
  1994. *
  1995. * @param column the column index
  1996. * @param useMergedCells whether to use the contents of merged cells when calculating the width of the column
  1997. */
  1998. @Override
  1999. public void autoSizeColumn(int column, boolean useMergedCells) {
  2000. double width = SheetUtil.getColumnWidth(this, column, useMergedCells);
  2001. if (width != -1) {
  2002. width *= 256;
  2003. int maxColumnWidth = 255 * 256; // The maximum column width for an individual cell is 255 characters
  2004. if (width > maxColumnWidth) {
  2005. width = maxColumnWidth;
  2006. }
  2007. setColumnWidth(column, (int) (width));
  2008. }
  2009. }
  2010. /**
  2011. * Returns cell comment for the specified row and column
  2012. *
  2013. * @return cell comment or <code>null</code> if not found
  2014. */
  2015. @Override
  2016. public HSSFComment getCellComment(CellAddress ref) {
  2017. return findCellComment(ref.getRow(), ref.getColumn());
  2018. }
  2019. /**
  2020. * Get a Hyperlink in this sheet anchored at row, column
  2021. *
  2022. * @param row The index of the row of the hyperlink, zero-based
  2023. * @param column the index of the column of the hyperlink, zero-based
  2024. * @return hyperlink if there is a hyperlink anchored at row, column; otherwise returns null
  2025. */
  2026. @Override
  2027. public HSSFHyperlink getHyperlink(int row, int column) {
  2028. for (RecordBase rec : _sheet.getRecords()) {
  2029. if (rec instanceof HyperlinkRecord) {
  2030. HyperlinkRecord link = (HyperlinkRecord) rec;
  2031. if (link.getFirstColumn() == column && link.getFirstRow() == row) {
  2032. return new HSSFHyperlink(link);
  2033. }
  2034. }
  2035. }
  2036. return null;
  2037. }
  2038. /**
  2039. * Get a Hyperlink in this sheet located in a cell specified by {code addr}
  2040. *
  2041. * @param addr The address of the cell containing the hyperlink
  2042. * @return hyperlink if there is a hyperlink anchored at {@code addr}; otherwise returns {@code null}
  2043. * @since POI 3.15 beta 3
  2044. */
  2045. @Override
  2046. public HSSFHyperlink getHyperlink(CellAddress addr) {
  2047. return getHyperlink(addr.getRow(), addr.getColumn());
  2048. }
  2049. /**
  2050. * Get a list of Hyperlinks in this sheet
  2051. *
  2052. * @return Hyperlinks for the sheet
  2053. */
  2054. @Override
  2055. public List<HSSFHyperlink> getHyperlinkList() {
  2056. final List<HSSFHyperlink> hyperlinkList = new ArrayList<>();
  2057. for (RecordBase rec : _sheet.getRecords()) {
  2058. if (rec instanceof HyperlinkRecord) {
  2059. HyperlinkRecord link = (HyperlinkRecord) rec;
  2060. hyperlinkList.add(new HSSFHyperlink(link));
  2061. }
  2062. }
  2063. return hyperlinkList;
  2064. }
  2065. /**
  2066. * Remove the underlying HyperlinkRecord from this sheet.
  2067. * If multiple HSSFHyperlinks refer to the same HyperlinkRecord, all HSSFHyperlinks will be removed.
  2068. *
  2069. * @param link the HSSFHyperlink wrapper around the HyperlinkRecord to remove
  2070. */
  2071. protected void removeHyperlink(HSSFHyperlink link) {
  2072. removeHyperlink(link.record);
  2073. }
  2074. /**
  2075. * Remove the underlying HyperlinkRecord from this sheet
  2076. *
  2077. * @param link the underlying HyperlinkRecord to remove from this sheet
  2078. */
  2079. protected void removeHyperlink(HyperlinkRecord link) {
  2080. for (Iterator<RecordBase> it = _sheet.getRecords().iterator(); it.hasNext();) {
  2081. RecordBase rec = it.next();
  2082. if (rec instanceof HyperlinkRecord) {
  2083. HyperlinkRecord recLink = (HyperlinkRecord) rec;
  2084. if (link == recLink) {
  2085. it.remove();
  2086. // if multiple HSSFHyperlinks refer to the same record
  2087. return;
  2088. }
  2089. }
  2090. }
  2091. }
  2092. @Override
  2093. public HSSFSheetConditionalFormatting getSheetConditionalFormatting() {
  2094. return new HSSFSheetConditionalFormatting(this);
  2095. }
  2096. /**
  2097. * Returns the name of this sheet
  2098. *
  2099. * @return the name of this sheet
  2100. */
  2101. @SuppressWarnings("resource")
  2102. @Override
  2103. public String getSheetName() {
  2104. HSSFWorkbook wb = getWorkbook();
  2105. int idx = wb.getSheetIndex(this);
  2106. return wb.getSheetName(idx);
  2107. }
  2108. /**
  2109. * Also creates cells if they don't exist
  2110. */
  2111. private CellRange<HSSFCell> getCellRange(CellRangeAddress range) {
  2112. int firstRow = range.getFirstRow();
  2113. int firstColumn = range.getFirstColumn();
  2114. int lastRow = range.getLastRow();
  2115. int lastColumn = range.getLastColumn();
  2116. int height = lastRow - firstRow + 1;
  2117. int width = lastColumn - firstColumn + 1;
  2118. List<HSSFCell> temp = new ArrayList<>(height * width);
  2119. for (int rowIn = firstRow; rowIn <= lastRow; rowIn++) {
  2120. for (int colIn = firstColumn; colIn <= lastColumn; colIn++) {
  2121. HSSFRow row = getRow(rowIn);
  2122. if (row == null) {
  2123. row = createRow(rowIn);
  2124. }
  2125. HSSFCell cell = row.getCell(colIn);
  2126. if (cell == null) {
  2127. cell = row.createCell(colIn);
  2128. }
  2129. temp.add(cell);
  2130. }
  2131. }
  2132. return SSCellRange.create(firstRow, firstColumn, height, width, temp, HSSFCell.class);
  2133. }
  2134. @Override
  2135. public CellRange<HSSFCell> setArrayFormula(String formula, CellRangeAddress range) {
  2136. // make sure the formula parses OK first
  2137. int sheetIndex = _workbook.getSheetIndex(this);
  2138. Ptg[] ptgs = HSSFFormulaParser.parse(formula, _workbook, FormulaType.ARRAY, sheetIndex);
  2139. CellRange<HSSFCell> cells = getCellRange(range);
  2140. for (HSSFCell c : cells) {
  2141. c.setCellArrayFormula(range);
  2142. }
  2143. HSSFCell mainArrayFormulaCell = cells.getTopLeftCell();
  2144. FormulaRecordAggregate agg = (FormulaRecordAggregate) mainArrayFormulaCell.getCellValueRecord();
  2145. agg.setArrayFormula(range, ptgs);
  2146. return cells;
  2147. }
  2148. @Override
  2149. public CellRange<HSSFCell> removeArrayFormula(Cell cell) {
  2150. if (cell.getSheet() != this) {
  2151. throw new IllegalArgumentException("Specified cell does not belong to this sheet.");
  2152. }
  2153. CellValueRecordInterface rec = ((HSSFCell) cell).getCellValueRecord();
  2154. if (!(rec instanceof FormulaRecordAggregate)) {
  2155. String ref = new CellReference(cell).formatAsString();
  2156. throw new IllegalArgumentException("Cell " + ref + " is not part of an array formula.");
  2157. }
  2158. FormulaRecordAggregate fra = (FormulaRecordAggregate) rec;
  2159. CellRangeAddress range = fra.removeArrayFormula(cell.getRowIndex(), cell.getColumnIndex());
  2160. CellRange<HSSFCell> result = getCellRange(range);
  2161. // clear all cells in the range
  2162. for (Cell c : result) {
  2163. c.setBlank();
  2164. }
  2165. return result;
  2166. }
  2167. @Override
  2168. public DataValidationHelper getDataValidationHelper() {
  2169. return new HSSFDataValidationHelper(this);
  2170. }
  2171. @Override
  2172. public HSSFAutoFilter setAutoFilter(CellRangeAddress range) {
  2173. InternalWorkbook workbook = _workbook.getWorkbook();
  2174. int sheetIndex = _workbook.getSheetIndex(this);
  2175. NameRecord name = workbook.getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, sheetIndex + 1);
  2176. if (name == null) {
  2177. name = workbook.createBuiltInName(NameRecord.BUILTIN_FILTER_DB, sheetIndex + 1);
  2178. }
  2179. int firstRow = range.getFirstRow();
  2180. // if row was not given when constructing the range...
  2181. if(firstRow == -1) {
  2182. firstRow = 0;
  2183. }
  2184. // The built-in name must consist of a single Area3d Ptg.
  2185. Area3DPtg ptg = new Area3DPtg(firstRow, range.getLastRow(),
  2186. range.getFirstColumn(), range.getLastColumn(),
  2187. false, false, false, false, sheetIndex);
  2188. name.setNameDefinition(new Ptg[]{ptg});
  2189. AutoFilterInfoRecord r = new AutoFilterInfoRecord();
  2190. // the number of columns that have AutoFilter enabled.
  2191. int numcols = 1 + range.getLastColumn() - range.getFirstColumn();
  2192. r.setNumEntries((short) numcols);
  2193. int idx = _sheet.findFirstRecordLocBySid(DimensionsRecord.sid);
  2194. _sheet.getRecords().add(idx, r);
  2195. //create a combobox control for each column
  2196. HSSFPatriarch p = createDrawingPatriarch();
  2197. final int firstColumn = range.getFirstColumn();
  2198. final int lastColumn = range.getLastColumn();
  2199. for (int col = firstColumn; col <= lastColumn; col++) {
  2200. p.createComboBox(new HSSFClientAnchor(0, 0, 0, 0,
  2201. (short) col, firstRow, (short) (col + 1), firstRow + 1));
  2202. }
  2203. return new HSSFAutoFilter(this);
  2204. }
  2205. protected HSSFComment findCellComment(int row, int column) {
  2206. HSSFPatriarch patriarch = getDrawingPatriarch();
  2207. if (null == patriarch) {
  2208. patriarch = createDrawingPatriarch();
  2209. }
  2210. return lookForComment(patriarch, row, column);
  2211. }
  2212. private HSSFComment lookForComment(HSSFShapeContainer container, int row, int column) {
  2213. for (Object object : container.getChildren()) {
  2214. HSSFShape shape = (HSSFShape) object;
  2215. if (shape instanceof HSSFShapeGroup) {
  2216. HSSFComment res = lookForComment((HSSFShapeContainer) shape, row, column);
  2217. if (null != res) {
  2218. return res;
  2219. }
  2220. continue;
  2221. }
  2222. if (shape instanceof HSSFComment) {
  2223. HSSFComment comment = (HSSFComment) shape;
  2224. if (comment.hasPosition() && comment.getColumn() == column && comment.getRow() == row) {
  2225. return comment;
  2226. }
  2227. }
  2228. }
  2229. return null;
  2230. }
  2231. /**
  2232. * Returns all cell comments on this sheet.
  2233. * @return A map of each Comment in the sheet, keyed on the cell address where
  2234. * the comment is located.
  2235. */
  2236. @Override
  2237. public Map<CellAddress, HSSFComment> getCellComments() {
  2238. HSSFPatriarch patriarch = getDrawingPatriarch();
  2239. if (null == patriarch) {
  2240. patriarch = createDrawingPatriarch();
  2241. }
  2242. Map<CellAddress, HSSFComment> locations = new TreeMap<>();
  2243. findCellCommentLocations(patriarch, locations);
  2244. return locations;
  2245. }
  2246. /**
  2247. * Finds all cell comments in this sheet and adds them to the specified locations map
  2248. *
  2249. * @param container a container that may contain HSSFComments
  2250. * @param locations the map to store the HSSFComments in
  2251. */
  2252. private void findCellCommentLocations(HSSFShapeContainer container, Map<CellAddress, HSSFComment> locations) {
  2253. for (Object object : container.getChildren()) {
  2254. HSSFShape shape = (HSSFShape) object;
  2255. if (shape instanceof HSSFShapeGroup) {
  2256. findCellCommentLocations((HSSFShapeGroup) shape, locations);
  2257. continue;
  2258. }
  2259. if (shape instanceof HSSFComment) {
  2260. HSSFComment comment = (HSSFComment) shape;
  2261. if (comment.hasPosition()) {
  2262. locations.put(new CellAddress(comment.getRow(), comment.getColumn()), comment);
  2263. }
  2264. }
  2265. }
  2266. }
  2267. @Override
  2268. public CellRangeAddress getRepeatingRows() {
  2269. return getRepeatingRowsOrColums(true);
  2270. }
  2271. @Override
  2272. public CellRangeAddress getRepeatingColumns() {
  2273. return getRepeatingRowsOrColums(false);
  2274. }
  2275. @Override
  2276. public void setRepeatingRows(CellRangeAddress rowRangeRef) {
  2277. CellRangeAddress columnRangeRef = getRepeatingColumns();
  2278. setRepeatingRowsAndColumns(rowRangeRef, columnRangeRef);
  2279. }
  2280. @Override
  2281. public void setRepeatingColumns(CellRangeAddress columnRangeRef) {
  2282. CellRangeAddress rowRangeRef = getRepeatingRows();
  2283. setRepeatingRowsAndColumns(rowRangeRef, columnRangeRef);
  2284. }
  2285. private void setRepeatingRowsAndColumns(
  2286. CellRangeAddress rowDef, CellRangeAddress colDef) {
  2287. int sheetIndex = _workbook.getSheetIndex(this);
  2288. int maxRowIndex = SpreadsheetVersion.EXCEL97.getLastRowIndex();
  2289. int maxColIndex = SpreadsheetVersion.EXCEL97.getLastColumnIndex();
  2290. int col1 = -1;
  2291. int col2 = -1;
  2292. int row1 = -1;
  2293. int row2 = -1;
  2294. if (rowDef != null) {
  2295. row1 = rowDef.getFirstRow();
  2296. row2 = rowDef.getLastRow();
  2297. if ((row1 == -1 && row2 != -1) || (row1 > row2)
  2298. || (row1 < 0 || row1 > maxRowIndex)
  2299. || (row2 < 0 || row2 > maxRowIndex)) {
  2300. throw new IllegalArgumentException("Invalid row range specification");
  2301. }
  2302. }
  2303. if (colDef != null) {
  2304. col1 = colDef.getFirstColumn();
  2305. col2 = colDef.getLastColumn();
  2306. if ((col1 == -1 && col2 != -1) || (col1 > col2)
  2307. || (col1 < 0 || col1 > maxColIndex)
  2308. || (col2 < 0 || col2 > maxColIndex)) {
  2309. throw new IllegalArgumentException("Invalid column range specification");
  2310. }
  2311. }
  2312. short externSheetIndex =
  2313. _workbook.getWorkbook().checkExternSheet(sheetIndex);
  2314. boolean setBoth = rowDef != null && colDef != null;
  2315. boolean removeAll = rowDef == null && colDef == null;
  2316. HSSFName name = _workbook.getBuiltInName(
  2317. NameRecord.BUILTIN_PRINT_TITLE, sheetIndex);
  2318. if (removeAll) {
  2319. if (name != null) {
  2320. _workbook.removeName(name);
  2321. }
  2322. return;
  2323. }
  2324. if (name == null) {
  2325. name = _workbook.createBuiltInName(
  2326. NameRecord.BUILTIN_PRINT_TITLE, sheetIndex);
  2327. }
  2328. List<Ptg> ptgList = new ArrayList<>();
  2329. if (setBoth) {
  2330. final int exprsSize = 2 * 11 + 1; // 2 * Area3DPtg.SIZE + UnionPtg.SIZE
  2331. ptgList.add(new MemFuncPtg(exprsSize));
  2332. }
  2333. if (colDef != null) {
  2334. Area3DPtg colArea = new Area3DPtg(0, maxRowIndex, col1, col2,
  2335. false, false, false, false, externSheetIndex);
  2336. ptgList.add(colArea);
  2337. }
  2338. if (rowDef != null) {
  2339. Area3DPtg rowArea = new Area3DPtg(row1, row2, 0, maxColIndex,
  2340. false, false, false, false, externSheetIndex);
  2341. ptgList.add(rowArea);
  2342. }
  2343. if (setBoth) {
  2344. ptgList.add(UnionPtg.instance);
  2345. }
  2346. Ptg[] ptgs = new Ptg[ptgList.size()];
  2347. ptgList.toArray(ptgs);
  2348. name.setNameDefinition(ptgs);
  2349. HSSFPrintSetup printSetup = getPrintSetup();
  2350. printSetup.setValidSettings(false);
  2351. setActive(true);
  2352. }
  2353. private CellRangeAddress getRepeatingRowsOrColums(boolean rows) {
  2354. NameRecord rec = getBuiltinNameRecord(NameRecord.BUILTIN_PRINT_TITLE);
  2355. if (rec == null) {
  2356. return null;
  2357. }
  2358. Ptg[] nameDefinition = rec.getNameDefinition();
  2359. if (nameDefinition == null) {
  2360. return null;
  2361. }
  2362. int maxRowIndex = SpreadsheetVersion.EXCEL97.getLastRowIndex();
  2363. int maxColIndex = SpreadsheetVersion.EXCEL97.getLastColumnIndex();
  2364. for (Ptg ptg : nameDefinition) {
  2365. if (ptg instanceof Area3DPtg) {
  2366. Area3DPtg areaPtg = (Area3DPtg) ptg;
  2367. if (areaPtg.getFirstColumn() == 0
  2368. && areaPtg.getLastColumn() == maxColIndex) {
  2369. if (rows) {
  2370. return new CellRangeAddress(
  2371. areaPtg.getFirstRow(), areaPtg.getLastRow(), -1, -1);
  2372. }
  2373. } else if (areaPtg.getFirstRow() == 0
  2374. && areaPtg.getLastRow() == maxRowIndex) {
  2375. if (!rows) {
  2376. return new CellRangeAddress(-1, -1,
  2377. areaPtg.getFirstColumn(), areaPtg.getLastColumn());
  2378. }
  2379. }
  2380. }
  2381. }
  2382. return null;
  2383. }
  2384. private NameRecord getBuiltinNameRecord(byte builtinCode) {
  2385. int sheetIndex = _workbook.getSheetIndex(this);
  2386. int recIndex =
  2387. _workbook.findExistingBuiltinNameRecordIdx(sheetIndex, builtinCode);
  2388. if (recIndex == -1) {
  2389. return null;
  2390. }
  2391. return _workbook.getNameRecord(recIndex);
  2392. }
  2393. /**
  2394. * Returns the column outline level. Increased as you
  2395. * put it into more groups (outlines), reduced as
  2396. * you take it out of them.
  2397. */
  2398. @Override
  2399. public int getColumnOutlineLevel(int columnIndex) {
  2400. return _sheet.getColumnOutlineLevel(columnIndex);
  2401. }
  2402. /**
  2403. * {@inheritDoc}
  2404. */
  2405. @Override
  2406. public CellAddress getActiveCell() {
  2407. int row = _sheet.getActiveCellRow();
  2408. int col = _sheet.getActiveCellCol();
  2409. return new CellAddress(row, col);
  2410. }
  2411. /**
  2412. * {@inheritDoc}
  2413. */
  2414. @Override
  2415. public void setActiveCell(CellAddress address) {
  2416. int row = address.getRow();
  2417. short col = (short) address.getColumn();
  2418. _sheet.setActiveCellRow(row);
  2419. _sheet.setActiveCellCol(col);
  2420. }
  2421. }