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

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