You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

HSSFSheet.java 92KB

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