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

HSSFSheet.java 70KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010
  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.TreeMap;
  21. import org.apache.poi.ddf.EscherRecord;
  22. import org.apache.poi.hssf.model.HSSFFormulaParser;
  23. import org.apache.poi.hssf.model.InternalSheet;
  24. import org.apache.poi.hssf.model.InternalWorkbook;
  25. import org.apache.poi.hssf.record.*;
  26. import org.apache.poi.hssf.record.aggregates.DataValidityTable;
  27. import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
  28. import org.apache.poi.hssf.record.aggregates.WorksheetProtectionBlock;
  29. import org.apache.poi.ss.formula.FormulaShifter;
  30. import org.apache.poi.ss.formula.ptg.Ptg;
  31. import org.apache.poi.ss.formula.ptg.Area3DPtg;
  32. import org.apache.poi.hssf.util.PaneInformation;
  33. import org.apache.poi.ss.SpreadsheetVersion;
  34. import org.apache.poi.ss.formula.FormulaType;
  35. import org.apache.poi.ss.usermodel.Cell;
  36. import org.apache.poi.ss.usermodel.CellRange;
  37. import org.apache.poi.ss.usermodel.CellStyle;
  38. import org.apache.poi.ss.usermodel.DataValidation;
  39. import org.apache.poi.ss.usermodel.DataValidationHelper;
  40. import org.apache.poi.ss.usermodel.Row;
  41. import org.apache.poi.ss.util.CellRangeAddress;
  42. import org.apache.poi.ss.util.CellReference;
  43. import org.apache.poi.ss.util.SSCellRange;
  44. import org.apache.poi.ss.util.SheetUtil;
  45. import org.apache.poi.util.POILogFactory;
  46. import org.apache.poi.util.POILogger;
  47. /**
  48. * High level representation of a worksheet.
  49. * @author Andrew C. Oliver (acoliver at apache dot org)
  50. * @author Glen Stampoultzis (glens at apache.org)
  51. * @author Libin Roman (romal at vistaportal.com)
  52. * @author Shawn Laubach (slaubach at apache dot org) (Just a little)
  53. * @author Jean-Pierre Paris (jean-pierre.paris at m4x dot org) (Just a little, too)
  54. * @author Yegor Kozlov (yegor at apache.org) (Autosizing columns)
  55. * @author Josh Micich
  56. * @author Petr Udalau(Petr.Udalau at exigenservices.com) - set/remove array formulas
  57. */
  58. public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
  59. private static final POILogger log = POILogFactory.getLogger(HSSFSheet.class);
  60. private static final int DEBUG = POILogger.DEBUG;
  61. /**
  62. * Used for compile-time optimization. This is the initial size for the collection of
  63. * rows. It is currently set to 20. If you generate larger sheets you may benefit
  64. * by setting this to a higher number and recompiling a custom edition of HSSFSheet.
  65. */
  66. public final static int INITIAL_CAPACITY = 20;
  67. /**
  68. * reference to the low level {@link InternalSheet} object
  69. */
  70. private final InternalSheet _sheet;
  71. /** stores rows by zero-based row number */
  72. private final TreeMap<Integer, HSSFRow> _rows;
  73. protected final InternalWorkbook _book;
  74. protected final HSSFWorkbook _workbook;
  75. private HSSFPatriarch _patriarch;
  76. private int _firstrow;
  77. private int _lastrow;
  78. /**
  79. * Creates new HSSFSheet - called by HSSFWorkbook to create a sheet from
  80. * scratch. You should not be calling this from application code (its protected anyhow).
  81. *
  82. * @param workbook - The HSSF Workbook object associated with the sheet.
  83. * @see org.apache.poi.hssf.usermodel.HSSFWorkbook#createSheet()
  84. */
  85. protected HSSFSheet(HSSFWorkbook workbook) {
  86. _sheet = InternalSheet.createSheet();
  87. _rows = new TreeMap<Integer, HSSFRow>();
  88. this._workbook = workbook;
  89. this._book = workbook.getWorkbook();
  90. }
  91. /**
  92. * Creates an HSSFSheet representing the given Sheet object. Should only be
  93. * called by HSSFWorkbook when reading in an exisiting file.
  94. *
  95. * @param workbook - The HSSF Workbook object associated with the sheet.
  96. * @param sheet - lowlevel Sheet object this sheet will represent
  97. * @see org.apache.poi.hssf.usermodel.HSSFWorkbook#createSheet()
  98. */
  99. protected HSSFSheet(HSSFWorkbook workbook, InternalSheet sheet) {
  100. this._sheet = sheet;
  101. _rows = new TreeMap<Integer, HSSFRow>();
  102. this._workbook = workbook;
  103. this._book = workbook.getWorkbook();
  104. setPropertiesFromSheet(sheet);
  105. }
  106. HSSFSheet cloneSheet(HSSFWorkbook workbook) {
  107. return new HSSFSheet(workbook, _sheet.cloneSheet());
  108. }
  109. /**
  110. * Return the parent workbook
  111. *
  112. * @return the parent workbook
  113. */
  114. public HSSFWorkbook getWorkbook(){
  115. return _workbook;
  116. }
  117. /**
  118. * used internally to set the properties given a Sheet object
  119. */
  120. private void setPropertiesFromSheet(InternalSheet sheet) {
  121. RowRecord row = sheet.getNextRow();
  122. boolean rowRecordsAlreadyPresent = row!=null;
  123. while (row != null) {
  124. createRowFromRecord(row);
  125. row = sheet.getNextRow();
  126. }
  127. Iterator<CellValueRecordInterface> iter = sheet.getCellValueIterator();
  128. long timestart = System.currentTimeMillis();
  129. if (log.check( POILogger.DEBUG ))
  130. log.log(DEBUG, "Time at start of cell creating in HSSF sheet = ",
  131. Long.valueOf(timestart));
  132. HSSFRow lastrow = null;
  133. // Add every cell to its row
  134. while (iter.hasNext()) {
  135. CellValueRecordInterface cval = iter.next();
  136. long cellstart = System.currentTimeMillis();
  137. HSSFRow hrow = lastrow;
  138. if (hrow == null || hrow.getRowNum() != cval.getRow()) {
  139. hrow = getRow( cval.getRow() );
  140. lastrow = hrow;
  141. if (hrow == null) {
  142. // Some tools (like Perl module Spreadsheet::WriteExcel - bug 41187) skip the RowRecords
  143. // Excel, OpenOffice.org and GoogleDocs are all OK with this, so POI should be too.
  144. if (rowRecordsAlreadyPresent) {
  145. // if at least one row record is present, all should be present.
  146. throw new RuntimeException("Unexpected missing row when some rows already present");
  147. }
  148. // create the row record on the fly now.
  149. RowRecord rowRec = new RowRecord(cval.getRow());
  150. sheet.addRow(rowRec);
  151. hrow = createRowFromRecord(rowRec);
  152. }
  153. }
  154. if (log.check( POILogger.DEBUG ))
  155. log.log( DEBUG, "record id = " + Integer.toHexString( ( (Record) cval ).getSid() ) );
  156. hrow.createCellFromRecord( cval );
  157. if (log.check( POILogger.DEBUG ))
  158. log.log( DEBUG, "record took ",
  159. Long.valueOf( System.currentTimeMillis() - cellstart ) );
  160. }
  161. if (log.check( POILogger.DEBUG ))
  162. log.log(DEBUG, "total sheet cell creation took ",
  163. Long.valueOf(System.currentTimeMillis() - timestart));
  164. }
  165. /**
  166. * Create a new row within the sheet and return the high level representation
  167. *
  168. * @param rownum row number
  169. * @return High level HSSFRow object representing a row in the sheet
  170. * @see org.apache.poi.hssf.usermodel.HSSFRow
  171. * @see #removeRow(org.apache.poi.ss.usermodel.Row)
  172. */
  173. public HSSFRow createRow(int rownum)
  174. {
  175. HSSFRow row = new HSSFRow(_workbook, this, rownum);
  176. // new rows inherit default height from the sheet
  177. row.setHeight(getDefaultRowHeight());
  178. addRow(row, true);
  179. return row;
  180. }
  181. /**
  182. * Used internally to create a high level Row object from a low level row object.
  183. * USed when reading an existing file
  184. * @param row low level record to represent as a high level Row and add to sheet
  185. * @return HSSFRow high level representation
  186. */
  187. private HSSFRow createRowFromRecord(RowRecord row)
  188. {
  189. HSSFRow hrow = new HSSFRow(_workbook, this, row);
  190. addRow(hrow, false);
  191. return hrow;
  192. }
  193. /**
  194. * Remove a row from this sheet. All cells contained in the row are removed as well
  195. *
  196. * @param row representing a row to remove.
  197. */
  198. public void removeRow(Row row) {
  199. HSSFRow hrow = (HSSFRow) row;
  200. if (row.getSheet() != this) {
  201. throw new IllegalArgumentException("Specified row does not belong to this sheet");
  202. }
  203. for(Cell cell : row) {
  204. HSSFCell xcell = (HSSFCell)cell;
  205. if(xcell.isPartOfArrayFormulaGroup()){
  206. String msg = "Row[rownum="+row.getRowNum()+"] contains cell(s) included in a multi-cell array formula. You cannot change part of an array.";
  207. xcell.notifyArrayFormulaChanging(msg);
  208. }
  209. }
  210. if (_rows.size() > 0) {
  211. Integer key = Integer.valueOf(row.getRowNum());
  212. HSSFRow removedRow = _rows.remove(key);
  213. if (removedRow != row) {
  214. //should not happen if the input argument is valid
  215. throw new IllegalArgumentException("Specified row does not belong to this sheet");
  216. }
  217. if (hrow.getRowNum() == getLastRowNum())
  218. {
  219. _lastrow = findLastRow(_lastrow);
  220. }
  221. if (hrow.getRowNum() == getFirstRowNum())
  222. {
  223. _firstrow = findFirstRow(_firstrow);
  224. }
  225. _sheet.removeRow(hrow.getRowRecord());
  226. }
  227. }
  228. /**
  229. * used internally to refresh the "last row" when the last row is removed.
  230. */
  231. private int findLastRow(int lastrow) {
  232. if (lastrow < 1) {
  233. return 0;
  234. }
  235. int rownum = lastrow - 1;
  236. HSSFRow r = getRow(rownum);
  237. while (r == null && rownum > 0) {
  238. r = getRow(--rownum);
  239. }
  240. if (r == null) {
  241. return 0;
  242. }
  243. return rownum;
  244. }
  245. /**
  246. * used internally to refresh the "first row" when the first row is removed.
  247. */
  248. private int findFirstRow(int firstrow)
  249. {
  250. int rownum = firstrow + 1;
  251. HSSFRow r = getRow(rownum);
  252. while (r == null && rownum <= getLastRowNum())
  253. {
  254. r = getRow(++rownum);
  255. }
  256. if (rownum > getLastRowNum())
  257. return 0;
  258. return rownum;
  259. }
  260. /**
  261. * add a row to the sheet
  262. *
  263. * @param addLow whether to add the row to the low level model - false if its already there
  264. */
  265. private void addRow(HSSFRow row, boolean addLow)
  266. {
  267. _rows.put(Integer.valueOf(row.getRowNum()), row);
  268. if (addLow)
  269. {
  270. _sheet.addRow(row.getRowRecord());
  271. }
  272. boolean firstRow = _rows.size() == 1;
  273. if (row.getRowNum() > getLastRowNum() || firstRow)
  274. {
  275. _lastrow = row.getRowNum();
  276. }
  277. if (row.getRowNum() < getFirstRowNum() || firstRow)
  278. {
  279. _firstrow = row.getRowNum();
  280. }
  281. }
  282. /**
  283. * Returns the logical row (not physical) 0-based. If you ask for a row that is not
  284. * defined you get a null. This is to say row 4 represents the fifth row on a sheet.
  285. * @param rowIndex row to get
  286. * @return HSSFRow representing the row number or null if its not defined on the sheet
  287. */
  288. public HSSFRow getRow(int rowIndex) {
  289. return _rows.get(Integer.valueOf(rowIndex));
  290. }
  291. /**
  292. * Returns the number of physically defined rows (NOT the number of rows in the sheet)
  293. */
  294. public int getPhysicalNumberOfRows() {
  295. return _rows.size();
  296. }
  297. /**
  298. * Gets the first row on the sheet
  299. * @return the number of the first logical row on the sheet, zero based
  300. */
  301. public int getFirstRowNum() {
  302. return _firstrow;
  303. }
  304. /**
  305. * Gets the number last row on the sheet.
  306. * Owing to idiosyncrasies in the excel file
  307. * format, if the result of calling this method
  308. * is zero, you can't tell if that means there
  309. * are zero rows on the sheet, or one at
  310. * position zero. For that case, additionally
  311. * call {@link #getPhysicalNumberOfRows()} to
  312. * tell if there is a row at position zero
  313. * or not.
  314. * @return the number of the last row contained in this sheet, zero based.
  315. */
  316. public int getLastRowNum() {
  317. return _lastrow;
  318. }
  319. /**
  320. * Creates a data validation object
  321. * @param dataValidation The Data validation object settings
  322. */
  323. public void addValidationData(DataValidation dataValidation) {
  324. if (dataValidation == null) {
  325. throw new IllegalArgumentException("objValidation must not be null");
  326. }
  327. HSSFDataValidation hssfDataValidation = (HSSFDataValidation)dataValidation;
  328. DataValidityTable dvt = _sheet.getOrCreateDataValidityTable();
  329. DVRecord dvRecord = hssfDataValidation.createDVRecord(this);
  330. dvt.addDataValidation(dvRecord);
  331. }
  332. /**
  333. * @deprecated (Sep 2008) use {@link #setColumnHidden(int, boolean)}
  334. */
  335. public void setColumnHidden(short columnIndex, boolean hidden) {
  336. setColumnHidden(columnIndex & 0xFFFF, hidden);
  337. }
  338. /**
  339. * @deprecated (Sep 2008) use {@link #isColumnHidden(int)}
  340. */
  341. public boolean isColumnHidden(short columnIndex) {
  342. return isColumnHidden(columnIndex & 0xFFFF);
  343. }
  344. /**
  345. * @deprecated (Sep 2008) use {@link #setColumnWidth(int, int)}
  346. */
  347. public void setColumnWidth(short columnIndex, short width) {
  348. setColumnWidth(columnIndex & 0xFFFF, width & 0xFFFF);
  349. }
  350. /**
  351. * @deprecated (Sep 2008) use {@link #getColumnWidth(int)}
  352. */
  353. public short getColumnWidth(short columnIndex) {
  354. return (short)getColumnWidth(columnIndex & 0xFFFF);
  355. }
  356. /**
  357. * @deprecated (Sep 2008) use {@link #setDefaultColumnWidth(int)}
  358. */
  359. public void setDefaultColumnWidth(short width) {
  360. setDefaultColumnWidth(width & 0xFFFF);
  361. }
  362. /**
  363. * Get the visibility state for a given column.
  364. * @param columnIndex - the column to get (0-based)
  365. * @param hidden - the visiblity state of the column
  366. */
  367. public void setColumnHidden(int columnIndex, boolean hidden) {
  368. _sheet.setColumnHidden(columnIndex, hidden);
  369. }
  370. /**
  371. * Get the hidden state for a given column.
  372. * @param columnIndex - the column to set (0-based)
  373. * @return hidden - <code>false</code> if the column is visible
  374. */
  375. public boolean isColumnHidden(int columnIndex) {
  376. return _sheet.isColumnHidden(columnIndex);
  377. }
  378. /**
  379. * Set the width (in units of 1/256th of a character width)
  380. *
  381. * <p>
  382. * The maximum column width for an individual cell is 255 characters.
  383. * This value represents the number of characters that can be displayed
  384. * in a cell that is formatted with the standard font (first font in the workbook).
  385. * </p>
  386. *
  387. * <p>
  388. * Character width is defined as the maximum digit width
  389. * of the numbers <code>0, 1, 2, ... 9</code> as rendered
  390. * using the default font (first font in the workbook).
  391. * <br/>
  392. * Unless you are using a very special font, the default character is '0' (zero),
  393. * this is true for Arial (default font font in HSSF) and Calibri (default font in XSSF)
  394. * </p>
  395. *
  396. * <p>
  397. * Please note, that the width set by this method includes 4 pixels of margin padding (two on each side),
  398. * plus 1 pixel padding for the gridlines (Section 3.3.1.12 of the OOXML spec).
  399. * This results is a slightly less value of visible characters than passed to this method (approx. 1/2 of a character).
  400. * </p>
  401. * <p>
  402. * To compute the actual number of visible characters,
  403. * Excel uses the following formula (Section 3.3.1.12 of the OOXML spec):
  404. * </p>
  405. * <code>
  406. * width = Truncate([{Number of Visible Characters} *
  407. * {Maximum Digit Width} + {5 pixel padding}]/{Maximum Digit Width}*256)/256
  408. * </code>
  409. * <p>Using the Calibri font as an example, the maximum digit width of 11 point font size is 7 pixels (at 96 dpi).
  410. * If you set a column width to be eight characters wide, e.g. <code>setColumnWidth(columnIndex, 8*256)</code>,
  411. * then the actual value of visible characters (the value shown in Excel) is derived from the following equation:
  412. * <code>
  413. Truncate([numChars*7+5]/7*256)/256 = 8;
  414. * </code>
  415. *
  416. * which gives <code>7.29</code>.
  417. *
  418. * @param columnIndex - the column to set (0-based)
  419. * @param width - the width in units of 1/256th of a character width
  420. * @throws IllegalArgumentException if width > 255*256 (the maximum column width in Excel is 255 characters)
  421. */
  422. public void setColumnWidth(int columnIndex, int width) {
  423. _sheet.setColumnWidth(columnIndex, width);
  424. }
  425. /**
  426. * get the width (in units of 1/256th of a character width )
  427. * @param columnIndex - the column to set (0-based)
  428. * @return width - the width in units of 1/256th of a character width
  429. */
  430. public int getColumnWidth(int columnIndex) {
  431. return _sheet.getColumnWidth(columnIndex);
  432. }
  433. /**
  434. * get the default column width for the sheet (if the columns do not define their own width) in
  435. * characters
  436. * @return default column width
  437. */
  438. public int getDefaultColumnWidth() {
  439. return _sheet.getDefaultColumnWidth();
  440. }
  441. /**
  442. * set the default column width for the sheet (if the columns do not define their own width) in
  443. * characters
  444. * @param width default column width
  445. */
  446. public void setDefaultColumnWidth(int width) {
  447. _sheet.setDefaultColumnWidth(width);
  448. }
  449. /**
  450. * get the default row height for the sheet (if the rows do not define their own height) in
  451. * twips (1/20 of a point)
  452. * @return default row height
  453. */
  454. public short getDefaultRowHeight() {
  455. return _sheet.getDefaultRowHeight();
  456. }
  457. /**
  458. * get the default row height for the sheet (if the rows do not define their own height) in
  459. * points.
  460. * @return default row height in points
  461. */
  462. public float getDefaultRowHeightInPoints()
  463. {
  464. return ((float)_sheet.getDefaultRowHeight() / 20);
  465. }
  466. /**
  467. * set the default row height for the sheet (if the rows do not define their own height) in
  468. * twips (1/20 of a point)
  469. * @param height default row height
  470. */
  471. public void setDefaultRowHeight(short height)
  472. {
  473. _sheet.setDefaultRowHeight(height);
  474. }
  475. /**
  476. * set the default row height for the sheet (if the rows do not define their own height) in
  477. * points
  478. * @param height default row height
  479. */
  480. public void setDefaultRowHeightInPoints(float height)
  481. {
  482. _sheet.setDefaultRowHeight((short) (height * 20));
  483. }
  484. /**
  485. * Returns the HSSFCellStyle that applies to the given
  486. * (0 based) column, or null if no style has been
  487. * set for that column
  488. */
  489. public HSSFCellStyle getColumnStyle(int column) {
  490. short styleIndex = _sheet.getXFIndexForColAt((short)column);
  491. if(styleIndex == 0xf) {
  492. // None set
  493. return null;
  494. }
  495. ExtendedFormatRecord xf = _book.getExFormatAt(styleIndex);
  496. return new HSSFCellStyle(styleIndex, xf, _book);
  497. }
  498. /**
  499. * get whether gridlines are printed.
  500. * @return true if printed
  501. */
  502. public boolean isGridsPrinted()
  503. {
  504. return _sheet.isGridsPrinted();
  505. }
  506. /**
  507. * set whether gridlines printed.
  508. * @param value false if not printed.
  509. */
  510. public void setGridsPrinted(boolean value)
  511. {
  512. _sheet.setGridsPrinted(value);
  513. }
  514. /**
  515. * @deprecated (Aug-2008) use <tt>CellRangeAddress</tt> instead of <tt>Region</tt>
  516. */
  517. public int addMergedRegion(org.apache.poi.ss.util.Region region)
  518. {
  519. return _sheet.addMergedRegion( region.getRowFrom(),
  520. region.getColumnFrom(),
  521. //(short) region.getRowTo(),
  522. region.getRowTo(),
  523. region.getColumnTo());
  524. }
  525. /**
  526. * adds a merged region of cells (hence those cells form one)
  527. * @param region (rowfrom/colfrom-rowto/colto) to merge
  528. * @return index of this region
  529. */
  530. public int addMergedRegion(CellRangeAddress region)
  531. {
  532. region.validate(SpreadsheetVersion.EXCEL97);
  533. // throw IllegalStateException if the argument CellRangeAddress intersects with
  534. // a multi-cell array formula defined in this sheet
  535. validateArrayFormulas(region);
  536. return _sheet.addMergedRegion( region.getFirstRow(),
  537. region.getFirstColumn(),
  538. region.getLastRow(),
  539. region.getLastColumn());
  540. }
  541. private void validateArrayFormulas(CellRangeAddress region){
  542. int firstRow = region.getFirstRow();
  543. int firstColumn = region.getFirstColumn();
  544. int lastRow = region.getLastRow();
  545. int lastColumn = region.getLastColumn();
  546. for (int rowIn = firstRow; rowIn <= lastRow; rowIn++) {
  547. for (int colIn = firstColumn; colIn <= lastColumn; colIn++) {
  548. HSSFRow row = getRow(rowIn);
  549. if (row == null) continue;
  550. HSSFCell cell = row.getCell(colIn);
  551. if(cell == null) continue;
  552. if(cell.isPartOfArrayFormulaGroup()){
  553. CellRangeAddress arrayRange = cell.getArrayFormulaRange();
  554. if (arrayRange.getNumberOfCells() > 1 &&
  555. ( arrayRange.isInRange(region.getFirstRow(), region.getFirstColumn()) ||
  556. arrayRange.isInRange(region.getFirstRow(), region.getFirstColumn())) ){
  557. String msg = "The range " + region.formatAsString() + " intersects with a multi-cell array formula. " +
  558. "You cannot merge cells of an array.";
  559. throw new IllegalStateException(msg);
  560. }
  561. }
  562. }
  563. }
  564. }
  565. /**
  566. * Control if Excel should be asked to recalculate all formulas on this sheet
  567. * when the workbook is opened.
  568. *
  569. * <p>
  570. * Calculating the formula values with {@link org.apache.poi.ss.usermodel.FormulaEvaluator} is the
  571. * recommended solution, but this may be used for certain cases where
  572. * evaluation in POI is not possible.
  573. * </p>
  574. *
  575. * <p>
  576. * It is recommended to force recalcuation of formulas on workbook level using
  577. * {@link org.apache.poi.ss.usermodel.Workbook#setForceFormulaRecalculation(boolean)}
  578. * to ensure that all cross-worksheet formuals and external dependencies are updated.
  579. * </p>
  580. * @param value true if the application will perform a full recalculation of
  581. * this worksheet values when the workbook is opened
  582. *
  583. * @see org.apache.poi.ss.usermodel.Workbook#setForceFormulaRecalculation(boolean)
  584. */
  585. public void setForceFormulaRecalculation(boolean value)
  586. {
  587. _sheet.setUncalced(value);
  588. }
  589. /**
  590. * Whether a record must be inserted or not at generation to indicate that
  591. * formula must be recalculated when workbook is opened.
  592. * @return true if an uncalced record must be inserted or not at generation
  593. */
  594. public boolean getForceFormulaRecalculation()
  595. {
  596. return _sheet.getUncalced();
  597. }
  598. /**
  599. * determines whether the output is vertically centered on the page.
  600. * @param value true to vertically center, false otherwise.
  601. */
  602. public void setVerticallyCenter(boolean value)
  603. {
  604. _sheet.getPageSettings().getVCenter().setVCenter(value);
  605. }
  606. /**
  607. * TODO: Boolean not needed, remove after next release
  608. * @deprecated (Mar-2008) use getVerticallyCenter() instead
  609. */
  610. public boolean getVerticallyCenter(boolean value) {
  611. return getVerticallyCenter();
  612. }
  613. /**
  614. * Determine whether printed output for this sheet will be vertically centered.
  615. */
  616. public boolean getVerticallyCenter()
  617. {
  618. return _sheet.getPageSettings().getVCenter().getVCenter();
  619. }
  620. /**
  621. * determines whether the output is horizontally centered on the page.
  622. * @param value true to horizontally center, false otherwise.
  623. */
  624. public void setHorizontallyCenter(boolean value)
  625. {
  626. _sheet.getPageSettings().getHCenter().setHCenter(value);
  627. }
  628. /**
  629. * Determine whether printed output for this sheet will be horizontally centered.
  630. */
  631. public boolean getHorizontallyCenter()
  632. {
  633. return _sheet.getPageSettings().getHCenter().getHCenter();
  634. }
  635. /**
  636. * Sets whether the worksheet is displayed from right to left instead of from left to right.
  637. *
  638. * @param value true for right to left, false otherwise.
  639. */
  640. public void setRightToLeft(boolean value)
  641. {
  642. _sheet.getWindowTwo().setArabic(value);
  643. }
  644. /**
  645. * Whether the text is displayed in right-to-left mode in the window
  646. *
  647. * @return whether the text is displayed in right-to-left mode in the window
  648. */
  649. public boolean isRightToLeft()
  650. {
  651. return _sheet.getWindowTwo().getArabic();
  652. }
  653. /**
  654. * removes a merged region of cells (hence letting them free)
  655. * @param index of the region to unmerge
  656. */
  657. public void removeMergedRegion(int index)
  658. {
  659. _sheet.removeMergedRegion(index);
  660. }
  661. /**
  662. * returns the number of merged regions
  663. * @return number of merged regions
  664. */
  665. public int getNumMergedRegions()
  666. {
  667. return _sheet.getNumMergedRegions();
  668. }
  669. /**
  670. * @deprecated (Aug-2008) use {@link HSSFSheet#getMergedRegion(int)}
  671. */
  672. public org.apache.poi.hssf.util.Region getMergedRegionAt(int index) {
  673. CellRangeAddress cra = getMergedRegion(index);
  674. return new org.apache.poi.hssf.util.Region(cra.getFirstRow(), (short)cra.getFirstColumn(),
  675. cra.getLastRow(), (short)cra.getLastColumn());
  676. }
  677. /**
  678. * @return the merged region at the specified index
  679. */
  680. public CellRangeAddress getMergedRegion(int index) {
  681. return _sheet.getMergedRegionAt(index);
  682. }
  683. /**
  684. * @return an iterator of the PHYSICAL rows. Meaning the 3rd element may not
  685. * be the third row if say for instance the second row is undefined.
  686. * Call getRowNum() on each row if you care which one it is.
  687. */
  688. public Iterator<Row> rowIterator() {
  689. @SuppressWarnings("unchecked") // can this clumsy generic syntax be improved?
  690. Iterator<Row> result = (Iterator<Row>)(Iterator<? extends Row>)_rows.values().iterator();
  691. return result;
  692. }
  693. /**
  694. * Alias for {@link #rowIterator()} to allow
  695. * foreach loops
  696. */
  697. public Iterator<Row> iterator() {
  698. return rowIterator();
  699. }
  700. /**
  701. * used internally in the API to get the low level Sheet record represented by this
  702. * Object.
  703. * @return Sheet - low level representation of this HSSFSheet.
  704. */
  705. InternalSheet getSheet() {
  706. return _sheet;
  707. }
  708. /**
  709. * whether alternate expression evaluation is on
  710. * @param b alternative expression evaluation or not
  711. */
  712. public void setAlternativeExpression(boolean b) {
  713. WSBoolRecord record =
  714. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  715. record.setAlternateExpression(b);
  716. }
  717. /**
  718. * whether alternative formula entry is on
  719. * @param b alternative formulas or not
  720. */
  721. public void setAlternativeFormula(boolean b) {
  722. WSBoolRecord record =
  723. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  724. record.setAlternateFormula(b);
  725. }
  726. /**
  727. * show automatic page breaks or not
  728. * @param b whether to show auto page breaks
  729. */
  730. public void setAutobreaks(boolean b) {
  731. WSBoolRecord record =
  732. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  733. record.setAutobreaks(b);
  734. }
  735. /**
  736. * set whether sheet is a dialog sheet or not
  737. * @param b isDialog or not
  738. */
  739. public void setDialog(boolean b) {
  740. WSBoolRecord record =
  741. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  742. record.setDialog(b);
  743. }
  744. /**
  745. * set whether to display the guts or not
  746. *
  747. * @param b guts or no guts (or glory)
  748. */
  749. public void setDisplayGuts(boolean b) {
  750. WSBoolRecord record =
  751. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  752. record.setDisplayGuts(b);
  753. }
  754. /**
  755. * fit to page option is on
  756. * @param b fit or not
  757. */
  758. public void setFitToPage(boolean b) {
  759. WSBoolRecord record =
  760. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  761. record.setFitToPage(b);
  762. }
  763. /**
  764. * set if row summaries appear below detail in the outline
  765. * @param b below or not
  766. */
  767. public void setRowSumsBelow(boolean b) {
  768. WSBoolRecord record =
  769. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  770. record.setRowSumsBelow(b);
  771. //setAlternateExpression must be set in conjuction with setRowSumsBelow
  772. record.setAlternateExpression(b);
  773. }
  774. /**
  775. * set if col summaries appear right of the detail in the outline
  776. * @param b right or not
  777. */
  778. public void setRowSumsRight(boolean b) {
  779. WSBoolRecord record =
  780. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  781. record.setRowSumsRight(b);
  782. }
  783. /**
  784. * whether alternate expression evaluation is on
  785. * @return alternative expression evaluation or not
  786. */
  787. public boolean getAlternateExpression() {
  788. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  789. .getAlternateExpression();
  790. }
  791. /**
  792. * whether alternative formula entry is on
  793. * @return alternative formulas or not
  794. */
  795. public boolean getAlternateFormula() {
  796. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  797. .getAlternateFormula();
  798. }
  799. /**
  800. * show automatic page breaks or not
  801. * @return whether to show auto page breaks
  802. */
  803. public boolean getAutobreaks() {
  804. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  805. .getAutobreaks();
  806. }
  807. /**
  808. * get whether sheet is a dialog sheet or not
  809. * @return isDialog or not
  810. */
  811. public boolean getDialog() {
  812. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  813. .getDialog();
  814. }
  815. /**
  816. * get whether to display the guts or not
  817. *
  818. * @return guts or no guts (or glory)
  819. */
  820. public boolean getDisplayGuts() {
  821. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  822. .getDisplayGuts();
  823. }
  824. /**
  825. * Gets the flag indicating whether the window should show 0 (zero) in cells containing zero value.
  826. * When false, cells with zero value appear blank instead of showing the number zero.
  827. * <p>
  828. * In Excel 2003 this option can be changed in the Options dialog on the View tab.
  829. * </p>
  830. * @return whether all zero values on the worksheet are displayed
  831. */
  832. public boolean isDisplayZeros(){
  833. return _sheet.getWindowTwo().getDisplayZeros();
  834. }
  835. /**
  836. * Set whether the window should show 0 (zero) in cells containing zero value.
  837. * When false, cells with zero value appear blank instead of showing the number zero.
  838. * <p>
  839. * In Excel 2003 this option can be set in the Options dialog on the View tab.
  840. * </p>
  841. * @param value whether to display or hide all zero values on the worksheet
  842. */
  843. public void setDisplayZeros(boolean value){
  844. _sheet.getWindowTwo().setDisplayZeros(value);
  845. }
  846. /**
  847. * fit to page option is on
  848. * @return fit or not
  849. */
  850. public boolean getFitToPage() {
  851. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  852. .getFitToPage();
  853. }
  854. /**
  855. * get if row summaries appear below detail in the outline
  856. * @return below or not
  857. */
  858. public boolean getRowSumsBelow() {
  859. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  860. .getRowSumsBelow();
  861. }
  862. /**
  863. * get if col summaries appear right of the detail in the outline
  864. * @return right or not
  865. */
  866. public boolean getRowSumsRight() {
  867. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  868. .getRowSumsRight();
  869. }
  870. /**
  871. * Returns whether gridlines are printed.
  872. * @return Gridlines are printed
  873. */
  874. public boolean isPrintGridlines() {
  875. return getSheet().getPrintGridlines().getPrintGridlines();
  876. }
  877. /**
  878. * Turns on or off the printing of gridlines.
  879. * @param newPrintGridlines boolean to turn on or off the printing of
  880. * gridlines
  881. */
  882. public void setPrintGridlines(boolean newPrintGridlines) {
  883. getSheet().getPrintGridlines().setPrintGridlines(newPrintGridlines);
  884. }
  885. /**
  886. * Gets the print setup object.
  887. * @return The user model for the print setup object.
  888. */
  889. public HSSFPrintSetup getPrintSetup() {
  890. return new HSSFPrintSetup(_sheet.getPageSettings().getPrintSetup());
  891. }
  892. public HSSFHeader getHeader() {
  893. return new HSSFHeader(_sheet.getPageSettings());
  894. }
  895. public HSSFFooter getFooter() {
  896. return new HSSFFooter(_sheet.getPageSettings());
  897. }
  898. /**
  899. * Note - this is not the same as whether the sheet is focused (isActive)
  900. * @return <code>true</code> if this sheet is currently selected
  901. */
  902. public boolean isSelected() {
  903. return getSheet().getWindowTwo().getSelected();
  904. }
  905. /**
  906. * Sets whether sheet is selected.
  907. * @param sel Whether to select the sheet or deselect the sheet.
  908. */
  909. public void setSelected(boolean sel) {
  910. getSheet().getWindowTwo().setSelected(sel);
  911. }
  912. /**
  913. * @return <code>true</code> if this sheet is currently focused
  914. */
  915. public boolean isActive() {
  916. return getSheet().getWindowTwo().isActive();
  917. }
  918. /**
  919. * Sets whether sheet is selected.
  920. * @param sel Whether to select the sheet or deselect the sheet.
  921. */
  922. public void setActive(boolean sel) {
  923. getSheet().getWindowTwo().setActive(sel);
  924. }
  925. /**
  926. * Gets the size of the margin in inches.
  927. * @param margin which margin to get
  928. * @return the size of the margin
  929. */
  930. public double getMargin(short margin) {
  931. switch (margin){
  932. case FooterMargin:
  933. return _sheet.getPageSettings().getPrintSetup().getFooterMargin();
  934. case HeaderMargin:
  935. return _sheet.getPageSettings().getPrintSetup().getHeaderMargin();
  936. default:
  937. return _sheet.getPageSettings().getMargin(margin);
  938. }
  939. }
  940. /**
  941. * Sets the size of the margin in inches.
  942. * @param margin which margin to get
  943. * @param size the size of the margin
  944. */
  945. public void setMargin(short margin, double size) {
  946. switch (margin){
  947. case FooterMargin:
  948. _sheet.getPageSettings().getPrintSetup().setFooterMargin(size);
  949. break;
  950. case HeaderMargin:
  951. _sheet.getPageSettings().getPrintSetup().setHeaderMargin(size);
  952. break;
  953. default:
  954. _sheet.getPageSettings().setMargin(margin, size);
  955. }
  956. }
  957. private WorksheetProtectionBlock getProtectionBlock() {
  958. return _sheet.getProtectionBlock();
  959. }
  960. /**
  961. * Answer whether protection is enabled or disabled
  962. * @return true => protection enabled; false => protection disabled
  963. */
  964. public boolean getProtect() {
  965. return getProtectionBlock().isSheetProtected();
  966. }
  967. /**
  968. * @return hashed password
  969. */
  970. public short getPassword() {
  971. return (short)getProtectionBlock().getPasswordHash();
  972. }
  973. /**
  974. * Answer whether object protection is enabled or disabled
  975. * @return true => protection enabled; false => protection disabled
  976. */
  977. public boolean getObjectProtect() {
  978. return getProtectionBlock().isObjectProtected();
  979. }
  980. /**
  981. * Answer whether scenario protection is enabled or disabled
  982. * @return true => protection enabled; false => protection disabled
  983. */
  984. public boolean getScenarioProtect() {
  985. return getProtectionBlock().isScenarioProtected();
  986. }
  987. /**
  988. * Sets the protection enabled as well as the password
  989. * @param password to set for protection. Pass <code>null</code> to remove protection
  990. */
  991. public void protectSheet(String password) {
  992. getProtectionBlock().protectSheet(password, true, true); //protect objs&scenarios(normal)
  993. }
  994. /**
  995. * Sets the zoom magnification for the sheet. The zoom is expressed as a
  996. * fraction. For example to express a zoom of 75% use 3 for the numerator
  997. * and 4 for the denominator.
  998. *
  999. * @param numerator The numerator for the zoom magnification.
  1000. * @param denominator The denominator for the zoom magnification.
  1001. */
  1002. public void setZoom( int numerator, int denominator)
  1003. {
  1004. if (numerator < 1 || numerator > 65535)
  1005. throw new IllegalArgumentException("Numerator must be greater than 1 and less than 65536");
  1006. if (denominator < 1 || denominator > 65535)
  1007. throw new IllegalArgumentException("Denominator must be greater than 1 and less than 65536");
  1008. SCLRecord sclRecord = new SCLRecord();
  1009. sclRecord.setNumerator((short)numerator);
  1010. sclRecord.setDenominator((short)denominator);
  1011. getSheet().setSCLRecord(sclRecord);
  1012. }
  1013. /**
  1014. * The top row in the visible view when the sheet is
  1015. * first viewed after opening it in a viewer
  1016. * @return short indicating the rownum (0 based) of the top row
  1017. */
  1018. public short getTopRow() {
  1019. return _sheet.getTopRow();
  1020. }
  1021. /**
  1022. * The left col in the visible view when the sheet is
  1023. * first viewed after opening it in a viewer
  1024. * @return short indicating the rownum (0 based) of the top row
  1025. */
  1026. public short getLeftCol() {
  1027. return _sheet.getLeftCol();
  1028. }
  1029. /**
  1030. * Sets desktop window pane display area, when the
  1031. * file is first opened in a viewer.
  1032. * @param toprow the top row to show in desktop window pane
  1033. * @param leftcol the left column to show in desktop window pane
  1034. */
  1035. public void showInPane(short toprow, short leftcol){
  1036. _sheet.setTopRow(toprow);
  1037. _sheet.setLeftCol(leftcol);
  1038. }
  1039. /**
  1040. * Shifts the merged regions left or right depending on mode
  1041. * <p>
  1042. * TODO: MODE , this is only row specific
  1043. * @param startRow
  1044. * @param endRow
  1045. * @param n
  1046. * @param isRow
  1047. */
  1048. protected void shiftMerged(int startRow, int endRow, int n, boolean isRow) {
  1049. List<CellRangeAddress> shiftedRegions = new ArrayList<CellRangeAddress>();
  1050. //move merged regions completely if they fall within the new region boundaries when they are shifted
  1051. for (int i = 0; i < getNumMergedRegions(); i++) {
  1052. CellRangeAddress merged = getMergedRegion(i);
  1053. boolean inStart= (merged.getFirstRow() >= startRow || merged.getLastRow() >= startRow);
  1054. boolean inEnd = (merged.getFirstRow() <= endRow || merged.getLastRow() <= endRow);
  1055. //don't check if it's not within the shifted area
  1056. if (!inStart || !inEnd) {
  1057. continue;
  1058. }
  1059. //only shift if the region outside the shifted rows is not merged too
  1060. if (!SheetUtil.containsCell(merged, startRow-1, 0) &&
  1061. !SheetUtil.containsCell(merged, endRow+1, 0)){
  1062. merged.setFirstRow(merged.getFirstRow()+n);
  1063. merged.setLastRow(merged.getLastRow()+n);
  1064. //have to remove/add it back
  1065. shiftedRegions.add(merged);
  1066. removeMergedRegion(i);
  1067. i = i -1; // we have to back up now since we removed one
  1068. }
  1069. }
  1070. //read so it doesn't get shifted again
  1071. Iterator<CellRangeAddress> iterator = shiftedRegions.iterator();
  1072. while (iterator.hasNext()) {
  1073. CellRangeAddress region = iterator.next();
  1074. this.addMergedRegion(region);
  1075. }
  1076. }
  1077. /**
  1078. * Shifts rows between startRow and endRow n number of rows.
  1079. * If you use a negative number, it will shift rows up.
  1080. * Code ensures that rows don't wrap around.
  1081. *
  1082. * Calls shiftRows(startRow, endRow, n, false, false);
  1083. *
  1084. * <p>
  1085. * Additionally shifts merged regions that are completely defined in these
  1086. * rows (ie. merged 2 cells on a row to be shifted).
  1087. * @param startRow the row to start shifting
  1088. * @param endRow the row to end shifting
  1089. * @param n the number of rows to shift
  1090. */
  1091. public void shiftRows( int startRow, int endRow, int n ) {
  1092. shiftRows(startRow, endRow, n, false, false);
  1093. }
  1094. /**
  1095. * Shifts rows between startRow and endRow n number of rows.
  1096. * If you use a negative number, it will shift rows up.
  1097. * Code ensures that rows don't wrap around
  1098. *
  1099. * <p>
  1100. * Additionally shifts merged regions that are completely defined in these
  1101. * rows (ie. merged 2 cells on a row to be shifted).
  1102. * <p>
  1103. * TODO Might want to add bounds checking here
  1104. * @param startRow the row to start shifting
  1105. * @param endRow the row to end shifting
  1106. * @param n the number of rows to shift
  1107. * @param copyRowHeight whether to copy the row height during the shift
  1108. * @param resetOriginalRowHeight whether to set the original row's height to the default
  1109. */
  1110. public void shiftRows( int startRow, int endRow, int n, boolean copyRowHeight, boolean resetOriginalRowHeight) {
  1111. shiftRows(startRow, endRow, n, copyRowHeight, resetOriginalRowHeight, true);
  1112. }
  1113. /**
  1114. * Shifts rows between startRow and endRow n number of rows.
  1115. * If you use a negative number, it will shift rows up.
  1116. * Code ensures that rows don't wrap around
  1117. *
  1118. * <p>
  1119. * Additionally shifts merged regions that are completely defined in these
  1120. * rows (ie. merged 2 cells on a row to be shifted).
  1121. * <p>
  1122. * TODO Might want to add bounds checking here
  1123. * @param startRow the row to start shifting
  1124. * @param endRow the row to end shifting
  1125. * @param n the number of rows to shift
  1126. * @param copyRowHeight whether to copy the row height during the shift
  1127. * @param resetOriginalRowHeight whether to set the original row's height to the default
  1128. * @param moveComments whether to move comments at the same time as the cells they are attached to
  1129. */
  1130. public void shiftRows(int startRow, int endRow, int n,
  1131. boolean copyRowHeight, boolean resetOriginalRowHeight, boolean moveComments) {
  1132. int s, inc;
  1133. if (n < 0) {
  1134. s = startRow;
  1135. inc = 1;
  1136. } else if (n > 0) {
  1137. s = endRow;
  1138. inc = -1;
  1139. } else {
  1140. // Nothing to do
  1141. return;
  1142. }
  1143. NoteRecord[] noteRecs;
  1144. if (moveComments) {
  1145. noteRecs = _sheet.getNoteRecords();
  1146. } else {
  1147. noteRecs = NoteRecord.EMPTY_ARRAY;
  1148. }
  1149. shiftMerged(startRow, endRow, n, true);
  1150. _sheet.getPageSettings().shiftRowBreaks(startRow, endRow, n);
  1151. for ( int rowNum = s; rowNum >= startRow && rowNum <= endRow && rowNum >= 0 && rowNum < 65536; rowNum += inc ) {
  1152. HSSFRow row = getRow( rowNum );
  1153. // notify all cells in this row that we are going to shift them,
  1154. // it can throw IllegalStateException if the operation is not allowed, for example,
  1155. // if the row contains cells included in a multi-cell array formula
  1156. if(row != null) notifyRowShifting(row);
  1157. HSSFRow row2Replace = getRow( rowNum + n );
  1158. if ( row2Replace == null )
  1159. row2Replace = createRow( rowNum + n );
  1160. // Remove all the old cells from the row we'll
  1161. // be writing too, before we start overwriting
  1162. // any cells. This avoids issues with cells
  1163. // changing type, and records not being correctly
  1164. // overwritten
  1165. row2Replace.removeAllCells();
  1166. // If this row doesn't exist, nothing needs to
  1167. // be done for the now empty destination row
  1168. if (row == null) continue; // Nothing to do for this row
  1169. // Fix up row heights if required
  1170. if (copyRowHeight) {
  1171. row2Replace.setHeight(row.getHeight());
  1172. }
  1173. if (resetOriginalRowHeight) {
  1174. row.setHeight((short)0xff);
  1175. }
  1176. // Copy each cell from the source row to
  1177. // the destination row
  1178. for(Iterator<Cell> cells = row.cellIterator(); cells.hasNext(); ) {
  1179. HSSFCell cell = (HSSFCell)cells.next();
  1180. row.removeCell( cell );
  1181. CellValueRecordInterface cellRecord = cell.getCellValueRecord();
  1182. cellRecord.setRow( rowNum + n );
  1183. row2Replace.createCellFromRecord( cellRecord );
  1184. _sheet.addValueRecord( rowNum + n, cellRecord );
  1185. HSSFHyperlink link = cell.getHyperlink();
  1186. if(link != null){
  1187. link.setFirstRow(link.getFirstRow() + n);
  1188. link.setLastRow(link.getLastRow() + n);
  1189. }
  1190. }
  1191. // Now zap all the cells in the source row
  1192. row.removeAllCells();
  1193. // Move comments from the source row to the
  1194. // destination row. Note that comments can
  1195. // exist for cells which are null
  1196. if(moveComments) {
  1197. // This code would get simpler if NoteRecords could be organised by HSSFRow.
  1198. for(int i=noteRecs.length-1; i>=0; i--) {
  1199. NoteRecord nr = noteRecs[i];
  1200. if (nr.getRow() != rowNum) {
  1201. continue;
  1202. }
  1203. HSSFComment comment = getCellComment(rowNum, nr.getColumn());
  1204. if (comment != null) {
  1205. comment.setRow(rowNum + n);
  1206. }
  1207. }
  1208. }
  1209. }
  1210. // Re-compute the first and last rows of the sheet as needed
  1211. if(n > 0) {
  1212. // Rows are moving down
  1213. if ( startRow == _firstrow ) {
  1214. // Need to walk forward to find the first non-blank row
  1215. _firstrow = Math.max( startRow + n, 0 );
  1216. for( int i=startRow+1; i < startRow+n; i++ ) {
  1217. if (getRow(i) != null) {
  1218. _firstrow = i;
  1219. break;
  1220. }
  1221. }
  1222. }
  1223. if ( endRow + n > _lastrow ) {
  1224. _lastrow = Math.min( endRow + n, SpreadsheetVersion.EXCEL97.getLastRowIndex() );
  1225. }
  1226. } else {
  1227. // Rows are moving up
  1228. if ( startRow + n < _firstrow ) {
  1229. _firstrow = Math.max( startRow + n, 0 );
  1230. }
  1231. if ( endRow == _lastrow ) {
  1232. // Need to walk backward to find the last non-blank row
  1233. _lastrow = Math.min( endRow + n, SpreadsheetVersion.EXCEL97.getLastRowIndex() );
  1234. for (int i=endRow-1; i > endRow+n; i++) {
  1235. if (getRow(i) != null) {
  1236. _lastrow = i;
  1237. break;
  1238. }
  1239. }
  1240. }
  1241. }
  1242. // Update any formulas on this sheet that point to
  1243. // rows which have been moved
  1244. int sheetIndex = _workbook.getSheetIndex(this);
  1245. short externSheetIndex = _book.checkExternSheet(sheetIndex);
  1246. FormulaShifter shifter = FormulaShifter.createForRowShift(externSheetIndex, startRow, endRow, n);
  1247. _sheet.updateFormulasAfterCellShift(shifter, externSheetIndex);
  1248. int nSheets = _workbook.getNumberOfSheets();
  1249. for(int i=0; i<nSheets; i++) {
  1250. InternalSheet otherSheet = _workbook.getSheetAt(i).getSheet();
  1251. if (otherSheet == this._sheet) {
  1252. continue;
  1253. }
  1254. short otherExtSheetIx = _book.checkExternSheet(i);
  1255. otherSheet.updateFormulasAfterCellShift(shifter, otherExtSheetIx);
  1256. }
  1257. _workbook.getWorkbook().updateNamesAfterCellShift(shifter);
  1258. }
  1259. protected void insertChartRecords(List<Record> records) {
  1260. int window2Loc = _sheet.findFirstRecordLocBySid(WindowTwoRecord.sid);
  1261. _sheet.getRecords().addAll(window2Loc, records);
  1262. }
  1263. private void notifyRowShifting(HSSFRow row){
  1264. String msg = "Row[rownum="+row.getRowNum()+"] contains cell(s) included in a multi-cell array formula. " +
  1265. "You cannot change part of an array.";
  1266. for(Cell cell : row){
  1267. HSSFCell hcell = (HSSFCell)cell;
  1268. if(hcell.isPartOfArrayFormulaGroup()){
  1269. hcell.notifyArrayFormulaChanging(msg);
  1270. }
  1271. }
  1272. }
  1273. /**
  1274. * Creates a split (freezepane). Any existing freezepane or split pane is overwritten.
  1275. *
  1276. * <p>
  1277. * If both colSplit and rowSplit are zero then the existing freeze pane is removed
  1278. * </p>
  1279. *
  1280. * @param colSplit Horizonatal position of split.
  1281. * @param rowSplit Vertical position of split.
  1282. * @param leftmostColumn Left column visible in right pane.
  1283. * @param topRow Top row visible in bottom pane
  1284. */
  1285. public void createFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow) {
  1286. validateColumn(colSplit);
  1287. validateRow(rowSplit);
  1288. if (leftmostColumn < colSplit) throw new IllegalArgumentException("leftmostColumn parameter must not be less than colSplit parameter");
  1289. if (topRow < rowSplit) throw new IllegalArgumentException("topRow parameter must not be less than leftmostColumn parameter");
  1290. getSheet().createFreezePane( colSplit, rowSplit, topRow, leftmostColumn );
  1291. }
  1292. /**
  1293. * Creates a split (freezepane). Any existing freezepane or split pane is overwritten.
  1294. *
  1295. * <p>
  1296. * If both colSplit and rowSplit are zero then the existing freeze pane is removed
  1297. * </p>
  1298. *
  1299. * @param colSplit Horizonatal position of split.
  1300. * @param rowSplit Vertical position of split.
  1301. */
  1302. public void createFreezePane(int colSplit, int rowSplit) {
  1303. createFreezePane(colSplit, rowSplit, colSplit, rowSplit);
  1304. }
  1305. /**
  1306. * Creates a split pane. Any existing freezepane or split pane is overwritten.
  1307. * @param xSplitPos Horizonatal position of split (in 1/20th of a point).
  1308. * @param ySplitPos Vertical position of split (in 1/20th of a point).
  1309. * @param topRow Top row visible in bottom pane
  1310. * @param leftmostColumn Left column visible in right pane.
  1311. * @param activePane Active pane. One of: PANE_LOWER_RIGHT,
  1312. * PANE_UPPER_RIGHT, PANE_LOWER_LEFT, PANE_UPPER_LEFT
  1313. * @see #PANE_LOWER_LEFT
  1314. * @see #PANE_LOWER_RIGHT
  1315. * @see #PANE_UPPER_LEFT
  1316. * @see #PANE_UPPER_RIGHT
  1317. */
  1318. public void createSplitPane(int xSplitPos, int ySplitPos, int leftmostColumn, int topRow, int activePane) {
  1319. getSheet().createSplitPane( xSplitPos, ySplitPos, topRow, leftmostColumn, activePane );
  1320. }
  1321. /**
  1322. * Returns the information regarding the currently configured pane (split or freeze).
  1323. * @return null if no pane configured, or the pane information.
  1324. */
  1325. public PaneInformation getPaneInformation() {
  1326. return getSheet().getPaneInformation();
  1327. }
  1328. /**
  1329. * Sets whether the gridlines are shown in a viewer.
  1330. * @param show whether to show gridlines or not
  1331. */
  1332. public void setDisplayGridlines(boolean show) {
  1333. _sheet.setDisplayGridlines(show);
  1334. }
  1335. /**
  1336. * Returns if gridlines are displayed.
  1337. * @return whether gridlines are displayed
  1338. */
  1339. public boolean isDisplayGridlines() {
  1340. return _sheet.isDisplayGridlines();
  1341. }
  1342. /**
  1343. * Sets whether the formulas are shown in a viewer.
  1344. * @param show whether to show formulas or not
  1345. */
  1346. public void setDisplayFormulas(boolean show) {
  1347. _sheet.setDisplayFormulas(show);
  1348. }
  1349. /**
  1350. * Returns if formulas are displayed.
  1351. * @return whether formulas are displayed
  1352. */
  1353. public boolean isDisplayFormulas() {
  1354. return _sheet.isDisplayFormulas();
  1355. }
  1356. /**
  1357. * Sets whether the RowColHeadings are shown in a viewer.
  1358. * @param show whether to show RowColHeadings or not
  1359. */
  1360. public void setDisplayRowColHeadings(boolean show) {
  1361. _sheet.setDisplayRowColHeadings(show);
  1362. }
  1363. /**
  1364. * Returns if RowColHeadings are displayed.
  1365. * @return whether RowColHeadings are displayed
  1366. */
  1367. public boolean isDisplayRowColHeadings() {
  1368. return _sheet.isDisplayRowColHeadings();
  1369. }
  1370. /**
  1371. * Sets a page break at the indicated row
  1372. * Breaks occur above the specified row and left of the specified column inclusive.
  1373. *
  1374. * For example, <code>sheet.setColumnBreak(2);</code> breaks the sheet into two parts
  1375. * with columns A,B,C in the first and D,E,... in the second. Simuilar, <code>sheet.setRowBreak(2);</code>
  1376. * breaks the sheet into two parts with first three rows (rownum=1...3) in the first part
  1377. * and rows starting with rownum=4 in the second.
  1378. *
  1379. * @param row the row to break, inclusive
  1380. */
  1381. public void setRowBreak(int row) {
  1382. validateRow(row);
  1383. _sheet.getPageSettings().setRowBreak(row, (short)0, (short)255);
  1384. }
  1385. /**
  1386. * @return <code>true</code> if there is a page break at the indicated row
  1387. */
  1388. public boolean isRowBroken(int row) {
  1389. return _sheet.getPageSettings().isRowBroken(row);
  1390. }
  1391. /**
  1392. * Removes the page break at the indicated row
  1393. */
  1394. public void removeRowBreak(int row) {
  1395. _sheet.getPageSettings().removeRowBreak(row);
  1396. }
  1397. /**
  1398. * @return row indexes of all the horizontal page breaks, never <code>null</code>
  1399. */
  1400. public int[] getRowBreaks() {
  1401. //we can probably cache this information, but this should be a sparsely used function
  1402. return _sheet.getPageSettings().getRowBreaks();
  1403. }
  1404. /**
  1405. * @return column indexes of all the vertical page breaks, never <code>null</code>
  1406. */
  1407. public int[] getColumnBreaks() {
  1408. //we can probably cache this information, but this should be a sparsely used function
  1409. return _sheet.getPageSettings().getColumnBreaks();
  1410. }
  1411. /**
  1412. * Sets a page break at the indicated column.
  1413. * Breaks occur above the specified row and left of the specified column inclusive.
  1414. *
  1415. * For example, <code>sheet.setColumnBreak(2);</code> breaks the sheet into two parts
  1416. * with columns A,B,C in the first and D,E,... in the second. Simuilar, <code>sheet.setRowBreak(2);</code>
  1417. * breaks the sheet into two parts with first three rows (rownum=1...3) in the first part
  1418. * and rows starting with rownum=4 in the second.
  1419. *
  1420. * @param column the column to break, inclusive
  1421. */
  1422. public void setColumnBreak(int column) {
  1423. validateColumn((short)column);
  1424. _sheet.getPageSettings().setColumnBreak((short)column, (short)0, (short) SpreadsheetVersion.EXCEL97.getLastRowIndex());
  1425. }
  1426. /**
  1427. * Determines if there is a page break at the indicated column
  1428. * @param column FIXME: Document this!
  1429. * @return FIXME: Document this!
  1430. */
  1431. public boolean isColumnBroken(int column) {
  1432. return _sheet.getPageSettings().isColumnBroken(column);
  1433. }
  1434. /**
  1435. * Removes a page break at the indicated column
  1436. * @param column
  1437. */
  1438. public void removeColumnBreak(int column) {
  1439. _sheet.getPageSettings().removeColumnBreak(column);
  1440. }
  1441. /**
  1442. * Runs a bounds check for row numbers
  1443. * @param row
  1444. */
  1445. protected void validateRow(int row) {
  1446. int maxrow = SpreadsheetVersion.EXCEL97.getLastRowIndex();
  1447. if (row > maxrow) throw new IllegalArgumentException("Maximum row number is " + maxrow);
  1448. if (row < 0) throw new IllegalArgumentException("Minumum row number is 0");
  1449. }
  1450. /**
  1451. * Runs a bounds check for column numbers
  1452. * @param column
  1453. */
  1454. protected void validateColumn(int column) {
  1455. int maxcol = SpreadsheetVersion.EXCEL97.getLastColumnIndex();
  1456. if (column > maxcol) throw new IllegalArgumentException("Maximum column number is " + maxcol);
  1457. if (column < 0) throw new IllegalArgumentException("Minimum column number is 0");
  1458. }
  1459. /**
  1460. * Aggregates the drawing records and dumps the escher record hierarchy
  1461. * to the standard output.
  1462. */
  1463. public void dumpDrawingRecords(boolean fat) {
  1464. _sheet.aggregateDrawingRecords(_book.getDrawingManager(), false);
  1465. EscherAggregate r = (EscherAggregate) getSheet().findFirstRecordBySid(EscherAggregate.sid);
  1466. List<EscherRecord> escherRecords = r.getEscherRecords();
  1467. PrintWriter w = new PrintWriter(System.out);
  1468. for (Iterator<EscherRecord> iterator = escherRecords.iterator(); iterator.hasNext();) {
  1469. EscherRecord escherRecord = iterator.next();
  1470. if (fat) {
  1471. System.out.println(escherRecord.toString());
  1472. } else {
  1473. escherRecord.display(w, 0);
  1474. }
  1475. }
  1476. w.flush();
  1477. }
  1478. /**
  1479. * Creates the top-level drawing patriarch. This will have
  1480. * the effect of removing any existing drawings on this
  1481. * sheet.
  1482. * This may then be used to add graphics or charts
  1483. * @return The new patriarch.
  1484. */
  1485. public HSSFPatriarch createDrawingPatriarch() {
  1486. if(_patriarch == null){
  1487. // Create the drawing group if it doesn't already exist.
  1488. _workbook.initDrawings();
  1489. if(_patriarch == null){
  1490. _sheet.aggregateDrawingRecords(_book.getDrawingManager(), true);
  1491. EscherAggregate agg = (EscherAggregate) _sheet.findFirstRecordBySid(EscherAggregate.sid);
  1492. _patriarch = new HSSFPatriarch(this, agg);
  1493. agg.setPatriarch(_patriarch);
  1494. }
  1495. }
  1496. return _patriarch;
  1497. }
  1498. /**
  1499. * Returns the agregate escher records for this sheet,
  1500. * it there is one.
  1501. * WARNING - calling this will trigger a parsing of the
  1502. * associated escher records. Any that aren't supported
  1503. * (such as charts and complex drawing types) will almost
  1504. * certainly be lost or corrupted when written out.
  1505. */
  1506. public EscherAggregate getDrawingEscherAggregate() {
  1507. _book.findDrawingGroup();
  1508. // If there's now no drawing manager, then there's
  1509. // no drawing escher records on the workbook
  1510. if(_book.getDrawingManager() == null) {
  1511. return null;
  1512. }
  1513. int found = _sheet.aggregateDrawingRecords(
  1514. _book.getDrawingManager(), false
  1515. );
  1516. if(found == -1) {
  1517. // Workbook has drawing stuff, but this sheet doesn't
  1518. return null;
  1519. }
  1520. // Grab our aggregate record, and wire it up
  1521. EscherAggregate agg = (EscherAggregate) _sheet.findFirstRecordBySid(EscherAggregate.sid);
  1522. return agg;
  1523. }
  1524. /**
  1525. * Returns the top-level drawing patriach, if there is
  1526. * one.
  1527. * This will hold any graphics or charts for the sheet.
  1528. * WARNING - calling this will trigger a parsing of the
  1529. * associated escher records. Any that aren't supported
  1530. * (such as charts and complex drawing types) will almost
  1531. * certainly be lost or corrupted when written out. Only
  1532. * use this with simple drawings, otherwise call
  1533. * {@link HSSFSheet#createDrawingPatriarch()} and
  1534. * start from scratch!
  1535. */
  1536. public HSSFPatriarch getDrawingPatriarch() {
  1537. if(_patriarch != null) return _patriarch;
  1538. EscherAggregate agg = getDrawingEscherAggregate();
  1539. if(agg == null) return null;
  1540. _patriarch = new HSSFPatriarch(this, agg);
  1541. _patriarch.buildShapeTree();
  1542. //HSSFShapeFactory.createShapeTree();
  1543. //agg.setPatriarch(_patriarch);
  1544. //EscherAggregate.createShapeTree(EscherAggregate.getMainSpgrContainer(agg), agg.getPatriarch(), agg);
  1545. // Have it process the records into high level objects
  1546. // as best it can do (this step may eat anything
  1547. // that isn't supported, you were warned...)
  1548. // agg.convertRecordsToUserModel();
  1549. // Return what we could cope with
  1550. return _patriarch;
  1551. }
  1552. /**
  1553. * @deprecated (Sep 2008) use {@link #setColumnGroupCollapsed(int, boolean)}
  1554. */
  1555. public void setColumnGroupCollapsed(short columnNumber, boolean collapsed) {
  1556. setColumnGroupCollapsed(columnNumber & 0xFFFF, collapsed);
  1557. }
  1558. /**
  1559. * @deprecated (Sep 2008) use {@link #groupColumn(int, int)}
  1560. */
  1561. public void groupColumn(short fromColumn, short toColumn) {
  1562. groupColumn(fromColumn & 0xFFFF, toColumn & 0xFFFF);
  1563. }
  1564. /**
  1565. * @deprecated (Sep 2008) use {@link #ungroupColumn(int, int)}
  1566. */
  1567. public void ungroupColumn(short fromColumn, short toColumn) {
  1568. ungroupColumn(fromColumn & 0xFFFF, toColumn & 0xFFFF);
  1569. }
  1570. /**
  1571. * Expands or collapses a column group.
  1572. *
  1573. * @param columnNumber One of the columns in the group.
  1574. * @param collapsed true = collapse group, false = expand group.
  1575. */
  1576. public void setColumnGroupCollapsed(int columnNumber, boolean collapsed) {
  1577. _sheet.setColumnGroupCollapsed(columnNumber, collapsed);
  1578. }
  1579. /**
  1580. * Create an outline for the provided column range.
  1581. *
  1582. * @param fromColumn beginning of the column range.
  1583. * @param toColumn end of the column range.
  1584. */
  1585. public void groupColumn(int fromColumn, int toColumn) {
  1586. _sheet.groupColumnRange(fromColumn, toColumn, true);
  1587. }
  1588. public void ungroupColumn(int fromColumn, int toColumn) {
  1589. _sheet.groupColumnRange(fromColumn, toColumn, false);
  1590. }
  1591. /**
  1592. * Tie a range of cell together so that they can be collapsed or expanded
  1593. *
  1594. * @param fromRow start row (0-based)
  1595. * @param toRow end row (0-based)
  1596. */
  1597. public void groupRow(int fromRow, int toRow) {
  1598. _sheet.groupRowRange(fromRow, toRow, true);
  1599. }
  1600. public void ungroupRow(int fromRow, int toRow) {
  1601. _sheet.groupRowRange(fromRow, toRow, false);
  1602. }
  1603. public void setRowGroupCollapsed(int rowIndex, boolean collapse) {
  1604. if (collapse) {
  1605. _sheet.getRowsAggregate().collapseRow(rowIndex);
  1606. } else {
  1607. _sheet.getRowsAggregate().expandRow(rowIndex);
  1608. }
  1609. }
  1610. /**
  1611. * Sets the default column style for a given column. POI will only apply this style to new cells added to the sheet.
  1612. *
  1613. * @param column the column index
  1614. * @param style the style to set
  1615. */
  1616. public void setDefaultColumnStyle(int column, CellStyle style) {
  1617. _sheet.setDefaultColumnStyle(column, ((HSSFCellStyle)style).getIndex());
  1618. }
  1619. /**
  1620. * Adjusts the column width to fit the contents.
  1621. *
  1622. * This process can be relatively slow on large sheets, so this should
  1623. * normally only be called once per column, at the end of your
  1624. * processing.
  1625. *
  1626. * @param column the column index
  1627. */
  1628. public void autoSizeColumn(int column) {
  1629. autoSizeColumn(column, false);
  1630. }
  1631. /**
  1632. * Adjusts the column width to fit the contents.
  1633. *
  1634. * This process can be relatively slow on large sheets, so this should
  1635. * normally only be called once per column, at the end of your
  1636. * processing.
  1637. *
  1638. * You can specify whether the content of merged cells should be considered or ignored.
  1639. * Default is to ignore merged cells.
  1640. *
  1641. * @param column the column index
  1642. * @param useMergedCells whether to use the contents of merged cells when calculating the width of the column
  1643. */
  1644. public void autoSizeColumn(int column, boolean useMergedCells) {
  1645. double width = SheetUtil.getColumnWidth(this, column, useMergedCells);
  1646. if (width != -1) {
  1647. width *= 256;
  1648. int maxColumnWidth = 255*256; // The maximum column width for an individual cell is 255 characters
  1649. if (width > maxColumnWidth) {
  1650. width = maxColumnWidth;
  1651. }
  1652. setColumnWidth(column, (int)(width));
  1653. }
  1654. }
  1655. /**
  1656. * Returns cell comment for the specified row and column
  1657. *
  1658. * @return cell comment or <code>null</code> if not found
  1659. */
  1660. public HSSFComment getCellComment(int row, int column) {
  1661. // Don't call findCellComment directly, otherwise
  1662. // two calls to this method will result in two
  1663. // new HSSFComment instances, which is bad
  1664. HSSFRow r = getRow(row);
  1665. if(r != null) {
  1666. HSSFCell c = r.getCell(column);
  1667. if(c != null) {
  1668. return c.getCellComment();
  1669. }
  1670. // No cell, so you will get new
  1671. // objects every time, sorry...
  1672. return HSSFCell.findCellComment(_sheet, row, column);
  1673. }
  1674. return null;
  1675. }
  1676. public HSSFSheetConditionalFormatting getSheetConditionalFormatting() {
  1677. return new HSSFSheetConditionalFormatting(this);
  1678. }
  1679. /**
  1680. * Returns the name of this sheet
  1681. *
  1682. * @return the name of this sheet
  1683. */
  1684. public String getSheetName() {
  1685. HSSFWorkbook wb = getWorkbook();
  1686. int idx = wb.getSheetIndex(this);
  1687. return wb.getSheetName(idx);
  1688. }
  1689. /**
  1690. * Also creates cells if they don't exist
  1691. */
  1692. private CellRange<HSSFCell> getCellRange(CellRangeAddress range) {
  1693. int firstRow = range.getFirstRow();
  1694. int firstColumn = range.getFirstColumn();
  1695. int lastRow = range.getLastRow();
  1696. int lastColumn = range.getLastColumn();
  1697. int height = lastRow - firstRow + 1;
  1698. int width = lastColumn - firstColumn + 1;
  1699. List<HSSFCell> temp = new ArrayList<HSSFCell>(height*width);
  1700. for (int rowIn = firstRow; rowIn <= lastRow; rowIn++) {
  1701. for (int colIn = firstColumn; colIn <= lastColumn; colIn++) {
  1702. HSSFRow row = getRow(rowIn);
  1703. if (row == null) {
  1704. row = createRow(rowIn);
  1705. }
  1706. HSSFCell cell = row.getCell(colIn);
  1707. if (cell == null) {
  1708. cell = row.createCell(colIn);
  1709. }
  1710. temp.add(cell);
  1711. }
  1712. }
  1713. return SSCellRange.create(firstRow, firstColumn, height, width, temp, HSSFCell.class);
  1714. }
  1715. public CellRange<HSSFCell> setArrayFormula(String formula, CellRangeAddress range) {
  1716. // make sure the formula parses OK first
  1717. int sheetIndex = _workbook.getSheetIndex(this);
  1718. Ptg[] ptgs = HSSFFormulaParser.parse(formula, _workbook, FormulaType.ARRAY, sheetIndex);
  1719. CellRange<HSSFCell> cells = getCellRange(range);
  1720. for (HSSFCell c : cells) {
  1721. c.setCellArrayFormula(range);
  1722. }
  1723. HSSFCell mainArrayFormulaCell = cells.getTopLeftCell();
  1724. FormulaRecordAggregate agg = (FormulaRecordAggregate)mainArrayFormulaCell.getCellValueRecord();
  1725. agg.setArrayFormula(range, ptgs);
  1726. return cells;
  1727. }
  1728. public CellRange<HSSFCell> removeArrayFormula(Cell cell) {
  1729. if (cell.getSheet() != this) {
  1730. throw new IllegalArgumentException("Specified cell does not belong to this sheet.");
  1731. }
  1732. CellValueRecordInterface rec = ((HSSFCell) cell).getCellValueRecord();
  1733. if (!(rec instanceof FormulaRecordAggregate)) {
  1734. String ref = new CellReference(cell).formatAsString();
  1735. throw new IllegalArgumentException("Cell " + ref + " is not part of an array formula.");
  1736. }
  1737. FormulaRecordAggregate fra = (FormulaRecordAggregate) rec;
  1738. CellRangeAddress range = fra.removeArrayFormula(cell.getRowIndex(), cell.getColumnIndex());
  1739. CellRange<HSSFCell> result = getCellRange(range);
  1740. // clear all cells in the range
  1741. for (Cell c : result) {
  1742. c.setCellType(Cell.CELL_TYPE_BLANK);
  1743. }
  1744. return result;
  1745. }
  1746. public DataValidationHelper getDataValidationHelper() {
  1747. return new HSSFDataValidationHelper(this);
  1748. }
  1749. public HSSFAutoFilter setAutoFilter(CellRangeAddress range) {
  1750. InternalWorkbook workbook = _workbook.getWorkbook();
  1751. int sheetIndex = _workbook.getSheetIndex(this);
  1752. NameRecord name = workbook.getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, sheetIndex+1);
  1753. if (name == null) {
  1754. name = workbook.createBuiltInName(NameRecord.BUILTIN_FILTER_DB, sheetIndex+1);
  1755. }
  1756. // The built-in name must consist of a single Area3d Ptg.
  1757. Area3DPtg ptg = new Area3DPtg(range.getFirstRow(), range.getLastRow(),
  1758. range.getFirstColumn(), range.getLastColumn(),
  1759. false, false, false, false, sheetIndex);
  1760. name.setNameDefinition(new Ptg[]{ptg});
  1761. AutoFilterInfoRecord r = new AutoFilterInfoRecord();
  1762. // the number of columns that have AutoFilter enabled.
  1763. int numcols = 1 + range.getLastColumn() - range.getFirstColumn();
  1764. r.setNumEntries((short)numcols);
  1765. int idx = _sheet.findFirstRecordLocBySid(DimensionsRecord.sid);
  1766. _sheet.getRecords().add(idx, r);
  1767. //create a combobox control for each column
  1768. HSSFPatriarch p = createDrawingPatriarch();
  1769. for(int col = range.getFirstColumn(); col <= range.getLastColumn(); col++){
  1770. p.createComboBox(new HSSFClientAnchor(0,0,0,0,
  1771. (short)col, range.getFirstRow(), (short)(col+1), range.getFirstRow()+1));
  1772. }
  1773. return new HSSFAutoFilter(this);
  1774. }
  1775. }