您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

HSSFSheet.java 87KB

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