Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

HSSFSheet.java 93KB

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