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 71KB

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