Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

HSSFSheet.java 81KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363
  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 the list of merged regions
  764. */
  765. public List<CellRangeAddress> getMergedRegions() {
  766. List<CellRangeAddress> addresses = new ArrayList<CellRangeAddress>();
  767. for (int i=0; i < _sheet.getNumMergedRegions(); i++) {
  768. addresses.add(_sheet.getMergedRegionAt(i));
  769. }
  770. return addresses;
  771. }
  772. /**
  773. * @return an iterator of the PHYSICAL rows. Meaning the 3rd element may not
  774. * be the third row if say for instance the second row is undefined.
  775. * Call getRowNum() on each row if you care which one it is.
  776. */
  777. public Iterator<Row> rowIterator() {
  778. @SuppressWarnings("unchecked") // can this clumsy generic syntax be improved?
  779. Iterator<Row> result = (Iterator<Row>) (Iterator<? extends Row>) _rows.values().iterator();
  780. return result;
  781. }
  782. /**
  783. * Alias for {@link #rowIterator()} to allow
  784. * foreach loops
  785. */
  786. public Iterator<Row> iterator() {
  787. return rowIterator();
  788. }
  789. /**
  790. * used internally in the API to get the low level Sheet record represented by this
  791. * Object.
  792. *
  793. * @return Sheet - low level representation of this HSSFSheet.
  794. */
  795. InternalSheet getSheet() {
  796. return _sheet;
  797. }
  798. /**
  799. * whether alternate expression evaluation is on
  800. *
  801. * @param b alternative expression evaluation or not
  802. */
  803. public void setAlternativeExpression(boolean b) {
  804. WSBoolRecord record =
  805. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  806. record.setAlternateExpression(b);
  807. }
  808. /**
  809. * whether alternative formula entry is on
  810. *
  811. * @param b alternative formulas or not
  812. */
  813. public void setAlternativeFormula(boolean b) {
  814. WSBoolRecord record =
  815. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  816. record.setAlternateFormula(b);
  817. }
  818. /**
  819. * show automatic page breaks or not
  820. *
  821. * @param b whether to show auto page breaks
  822. */
  823. public void setAutobreaks(boolean b) {
  824. WSBoolRecord record =
  825. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  826. record.setAutobreaks(b);
  827. }
  828. /**
  829. * set whether sheet is a dialog sheet or not
  830. *
  831. * @param b isDialog or not
  832. */
  833. public void setDialog(boolean b) {
  834. WSBoolRecord record =
  835. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  836. record.setDialog(b);
  837. }
  838. /**
  839. * set whether to display the guts or not
  840. *
  841. * @param b guts or no guts (or glory)
  842. */
  843. public void setDisplayGuts(boolean b) {
  844. WSBoolRecord record =
  845. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  846. record.setDisplayGuts(b);
  847. }
  848. /**
  849. * fit to page option is on
  850. *
  851. * @param b fit or not
  852. */
  853. public void setFitToPage(boolean b) {
  854. WSBoolRecord record =
  855. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  856. record.setFitToPage(b);
  857. }
  858. /**
  859. * set if row summaries appear below detail in the outline
  860. *
  861. * @param b below or not
  862. */
  863. public void setRowSumsBelow(boolean b) {
  864. WSBoolRecord record =
  865. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  866. record.setRowSumsBelow(b);
  867. //setAlternateExpression must be set in conjuction with setRowSumsBelow
  868. record.setAlternateExpression(b);
  869. }
  870. /**
  871. * set if col summaries appear right of the detail in the outline
  872. *
  873. * @param b right or not
  874. */
  875. public void setRowSumsRight(boolean b) {
  876. WSBoolRecord record =
  877. (WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid);
  878. record.setRowSumsRight(b);
  879. }
  880. /**
  881. * whether alternate expression evaluation is on
  882. *
  883. * @return alternative expression evaluation or not
  884. */
  885. public boolean getAlternateExpression() {
  886. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  887. .getAlternateExpression();
  888. }
  889. /**
  890. * whether alternative formula entry is on
  891. *
  892. * @return alternative formulas or not
  893. */
  894. public boolean getAlternateFormula() {
  895. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  896. .getAlternateFormula();
  897. }
  898. /**
  899. * show automatic page breaks or not
  900. *
  901. * @return whether to show auto page breaks
  902. */
  903. public boolean getAutobreaks() {
  904. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  905. .getAutobreaks();
  906. }
  907. /**
  908. * get whether sheet is a dialog sheet or not
  909. *
  910. * @return isDialog or not
  911. */
  912. public boolean getDialog() {
  913. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  914. .getDialog();
  915. }
  916. /**
  917. * get whether to display the guts or not
  918. *
  919. * @return guts or no guts (or glory)
  920. */
  921. public boolean getDisplayGuts() {
  922. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  923. .getDisplayGuts();
  924. }
  925. /**
  926. * Gets the flag indicating whether the window should show 0 (zero) in cells containing zero value.
  927. * When false, cells with zero value appear blank instead of showing the number zero.
  928. * <p>
  929. * In Excel 2003 this option can be changed in the Options dialog on the View tab.
  930. * </p>
  931. *
  932. * @return whether all zero values on the worksheet are displayed
  933. */
  934. public boolean isDisplayZeros() {
  935. return _sheet.getWindowTwo().getDisplayZeros();
  936. }
  937. /**
  938. * Set whether the window should show 0 (zero) in cells containing zero value.
  939. * When false, cells with zero value appear blank instead of showing the number zero.
  940. * <p>
  941. * In Excel 2003 this option can be set in the Options dialog on the View tab.
  942. * </p>
  943. *
  944. * @param value whether to display or hide all zero values on the worksheet
  945. */
  946. public void setDisplayZeros(boolean value) {
  947. _sheet.getWindowTwo().setDisplayZeros(value);
  948. }
  949. /**
  950. * fit to page option is on
  951. *
  952. * @return fit or not
  953. */
  954. public boolean getFitToPage() {
  955. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  956. .getFitToPage();
  957. }
  958. /**
  959. * get if row summaries appear below detail in the outline
  960. *
  961. * @return below or not
  962. */
  963. public boolean getRowSumsBelow() {
  964. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  965. .getRowSumsBelow();
  966. }
  967. /**
  968. * get if col summaries appear right of the detail in the outline
  969. *
  970. * @return right or not
  971. */
  972. public boolean getRowSumsRight() {
  973. return ((WSBoolRecord) _sheet.findFirstRecordBySid(WSBoolRecord.sid))
  974. .getRowSumsRight();
  975. }
  976. /**
  977. * Returns whether gridlines are printed.
  978. *
  979. * @return Gridlines are printed
  980. */
  981. public boolean isPrintGridlines() {
  982. return getSheet().getPrintGridlines().getPrintGridlines();
  983. }
  984. /**
  985. * Turns on or off the printing of gridlines.
  986. *
  987. * @param newPrintGridlines boolean to turn on or off the printing of
  988. * gridlines
  989. */
  990. public void setPrintGridlines(boolean newPrintGridlines) {
  991. getSheet().getPrintGridlines().setPrintGridlines(newPrintGridlines);
  992. }
  993. /**
  994. * Gets the print setup object.
  995. *
  996. * @return The user model for the print setup object.
  997. */
  998. public HSSFPrintSetup getPrintSetup() {
  999. return new HSSFPrintSetup(_sheet.getPageSettings().getPrintSetup());
  1000. }
  1001. public HSSFHeader getHeader() {
  1002. return new HSSFHeader(_sheet.getPageSettings());
  1003. }
  1004. public HSSFFooter getFooter() {
  1005. return new HSSFFooter(_sheet.getPageSettings());
  1006. }
  1007. /**
  1008. * Note - this is not the same as whether the sheet is focused (isActive)
  1009. *
  1010. * @return <code>true</code> if this sheet is currently selected
  1011. */
  1012. public boolean isSelected() {
  1013. return getSheet().getWindowTwo().getSelected();
  1014. }
  1015. /**
  1016. * Sets whether sheet is selected.
  1017. *
  1018. * @param sel Whether to select the sheet or deselect the sheet.
  1019. */
  1020. public void setSelected(boolean sel) {
  1021. getSheet().getWindowTwo().setSelected(sel);
  1022. }
  1023. /**
  1024. * @return <code>true</code> if this sheet is currently focused
  1025. */
  1026. public boolean isActive() {
  1027. return getSheet().getWindowTwo().isActive();
  1028. }
  1029. /**
  1030. * Sets whether sheet is selected.
  1031. *
  1032. * @param sel Whether to select the sheet or deselect the sheet.
  1033. */
  1034. public void setActive(boolean sel) {
  1035. getSheet().getWindowTwo().setActive(sel);
  1036. }
  1037. /**
  1038. * Gets the size of the margin in inches.
  1039. *
  1040. * @param margin which margin to get
  1041. * @return the size of the margin
  1042. */
  1043. public double getMargin(short margin) {
  1044. switch (margin) {
  1045. case FooterMargin:
  1046. return _sheet.getPageSettings().getPrintSetup().getFooterMargin();
  1047. case HeaderMargin:
  1048. return _sheet.getPageSettings().getPrintSetup().getHeaderMargin();
  1049. default:
  1050. return _sheet.getPageSettings().getMargin(margin);
  1051. }
  1052. }
  1053. /**
  1054. * Sets the size of the margin in inches.
  1055. *
  1056. * @param margin which margin to get
  1057. * @param size the size of the margin
  1058. */
  1059. public void setMargin(short margin, double size) {
  1060. switch (margin) {
  1061. case FooterMargin:
  1062. _sheet.getPageSettings().getPrintSetup().setFooterMargin(size);
  1063. break;
  1064. case HeaderMargin:
  1065. _sheet.getPageSettings().getPrintSetup().setHeaderMargin(size);
  1066. break;
  1067. default:
  1068. _sheet.getPageSettings().setMargin(margin, size);
  1069. }
  1070. }
  1071. private WorksheetProtectionBlock getProtectionBlock() {
  1072. return _sheet.getProtectionBlock();
  1073. }
  1074. /**
  1075. * Answer whether protection is enabled or disabled
  1076. *
  1077. * @return true => protection enabled; false => protection disabled
  1078. */
  1079. public boolean getProtect() {
  1080. return getProtectionBlock().isSheetProtected();
  1081. }
  1082. /**
  1083. * @return hashed password
  1084. */
  1085. public short getPassword() {
  1086. return (short) getProtectionBlock().getPasswordHash();
  1087. }
  1088. /**
  1089. * Answer whether object protection is enabled or disabled
  1090. *
  1091. * @return true => protection enabled; false => protection disabled
  1092. */
  1093. public boolean getObjectProtect() {
  1094. return getProtectionBlock().isObjectProtected();
  1095. }
  1096. /**
  1097. * Answer whether scenario protection is enabled or disabled
  1098. *
  1099. * @return true => protection enabled; false => protection disabled
  1100. */
  1101. public boolean getScenarioProtect() {
  1102. return getProtectionBlock().isScenarioProtected();
  1103. }
  1104. /**
  1105. * Sets the protection enabled as well as the password
  1106. *
  1107. * @param password to set for protection. Pass <code>null</code> to remove protection
  1108. */
  1109. public void protectSheet(String password) {
  1110. getProtectionBlock().protectSheet(password, true, true); //protect objs&scenarios(normal)
  1111. }
  1112. /**
  1113. * Sets the zoom magnification for the sheet. The zoom is expressed as a
  1114. * fraction. For example to express a zoom of 75% use 3 for the numerator
  1115. * and 4 for the denominator.
  1116. *
  1117. * @param numerator The numerator for the zoom magnification.
  1118. * @param denominator The denominator for the zoom magnification.
  1119. */
  1120. public void setZoom(int numerator, int denominator) {
  1121. if (numerator < 1 || numerator > 65535)
  1122. throw new IllegalArgumentException("Numerator must be greater than 0 and less than 65536");
  1123. if (denominator < 1 || denominator > 65535)
  1124. throw new IllegalArgumentException("Denominator must be greater than 0 and less than 65536");
  1125. SCLRecord sclRecord = new SCLRecord();
  1126. sclRecord.setNumerator((short) numerator);
  1127. sclRecord.setDenominator((short) denominator);
  1128. getSheet().setSCLRecord(sclRecord);
  1129. }
  1130. /**
  1131. * The top row in the visible view when the sheet is
  1132. * first viewed after opening it in a viewer
  1133. *
  1134. * @return short indicating the rownum (0 based) of the top row
  1135. */
  1136. public short getTopRow() {
  1137. return _sheet.getTopRow();
  1138. }
  1139. /**
  1140. * The left col in the visible view when the sheet is
  1141. * first viewed after opening it in a viewer
  1142. *
  1143. * @return short indicating the rownum (0 based) of the top row
  1144. */
  1145. public short getLeftCol() {
  1146. return _sheet.getLeftCol();
  1147. }
  1148. /**
  1149. * Sets desktop window pane display area, when the
  1150. * file is first opened in a viewer.
  1151. *
  1152. * @param toprow the top row to show in desktop window pane
  1153. * @param leftcol the left column to show in desktop window pane
  1154. */
  1155. public void showInPane(int toprow, int leftcol) {
  1156. int maxrow = SpreadsheetVersion.EXCEL97.getLastRowIndex();
  1157. if (toprow > maxrow) throw new IllegalArgumentException("Maximum row number is " + maxrow);
  1158. showInPane((short)toprow, (short)leftcol);
  1159. }
  1160. /**
  1161. * Sets desktop window pane display area, when the
  1162. * file is first opened in a viewer.
  1163. *
  1164. * @param toprow the top row to show in desktop window pane
  1165. * @param leftcol the left column to show in desktop window pane
  1166. */
  1167. public void showInPane(short toprow, short leftcol) {
  1168. _sheet.setTopRow(toprow);
  1169. _sheet.setLeftCol(leftcol);
  1170. }
  1171. /**
  1172. * Shifts the merged regions left or right depending on mode
  1173. * <p/>
  1174. * TODO: MODE , this is only row specific
  1175. *
  1176. * @param startRow
  1177. * @param endRow
  1178. * @param n
  1179. * @param isRow
  1180. */
  1181. protected void shiftMerged(int startRow, int endRow, int n, boolean isRow) {
  1182. List<CellRangeAddress> shiftedRegions = new ArrayList<CellRangeAddress>();
  1183. //move merged regions completely if they fall within the new region boundaries when they are shifted
  1184. for (int i = 0; i < getNumMergedRegions(); i++) {
  1185. CellRangeAddress merged = getMergedRegion(i);
  1186. boolean inStart = (merged.getFirstRow() >= startRow || merged.getLastRow() >= startRow);
  1187. boolean inEnd = (merged.getFirstRow() <= endRow || merged.getLastRow() <= endRow);
  1188. //don't check if it's not within the shifted area
  1189. if (!inStart || !inEnd) {
  1190. continue;
  1191. }
  1192. //only shift if the region outside the shifted rows is not merged too
  1193. if (!SheetUtil.containsCell(merged, startRow - 1, 0) &&
  1194. !SheetUtil.containsCell(merged, endRow + 1, 0)) {
  1195. merged.setFirstRow(merged.getFirstRow() + n);
  1196. merged.setLastRow(merged.getLastRow() + n);
  1197. //have to remove/add it back
  1198. shiftedRegions.add(merged);
  1199. removeMergedRegion(i);
  1200. i = i - 1; // we have to back up now since we removed one
  1201. }
  1202. }
  1203. //read so it doesn't get shifted again
  1204. Iterator<CellRangeAddress> iterator = shiftedRegions.iterator();
  1205. while (iterator.hasNext()) {
  1206. CellRangeAddress region = iterator.next();
  1207. this.addMergedRegion(region);
  1208. }
  1209. }
  1210. /**
  1211. * Shifts rows between startRow and endRow n number of rows.
  1212. * If you use a negative number, it will shift rows up.
  1213. * Code ensures that rows don't wrap around.
  1214. * <p/>
  1215. * Calls shiftRows(startRow, endRow, n, false, false);
  1216. * <p/>
  1217. * <p/>
  1218. * Additionally shifts merged regions that are completely defined in these
  1219. * rows (ie. merged 2 cells on a row to be shifted).
  1220. *
  1221. * @param startRow the row to start shifting
  1222. * @param endRow the row to end shifting
  1223. * @param n the number of rows to shift
  1224. */
  1225. public void shiftRows(int startRow, int endRow, int n) {
  1226. shiftRows(startRow, endRow, n, false, false);
  1227. }
  1228. /**
  1229. * Shifts rows between startRow and endRow n number of rows.
  1230. * If you use a negative number, it will shift rows up.
  1231. * Code ensures that rows don't wrap around
  1232. * <p/>
  1233. * <p/>
  1234. * Additionally shifts merged regions that are completely defined in these
  1235. * rows (ie. merged 2 cells on a row to be shifted).
  1236. * <p/>
  1237. * TODO Might want to add bounds checking here
  1238. *
  1239. * @param startRow the row to start shifting
  1240. * @param endRow the row to end shifting
  1241. * @param n the number of rows to shift
  1242. * @param copyRowHeight whether to copy the row height during the shift
  1243. * @param resetOriginalRowHeight whether to set the original row's height to the default
  1244. */
  1245. public void shiftRows(int startRow, int endRow, int n, boolean copyRowHeight, boolean resetOriginalRowHeight) {
  1246. shiftRows(startRow, endRow, n, copyRowHeight, resetOriginalRowHeight, true);
  1247. }
  1248. /**
  1249. * Shifts rows between startRow and endRow n number of rows.
  1250. * If you use a negative number, it will shift rows up.
  1251. * Code ensures that rows don't wrap around
  1252. * <p/>
  1253. * <p/>
  1254. * Additionally shifts merged regions that are completely defined in these
  1255. * rows (ie. merged 2 cells on a row to be shifted).
  1256. * <p/>
  1257. * TODO Might want to add bounds checking here
  1258. *
  1259. * @param startRow the row to start shifting
  1260. * @param endRow the row to end shifting
  1261. * @param n the number of rows to shift
  1262. * @param copyRowHeight whether to copy the row height during the shift
  1263. * @param resetOriginalRowHeight whether to set the original row's height to the default
  1264. * @param moveComments whether to move comments at the same time as the cells they are attached to
  1265. */
  1266. public void shiftRows(int startRow, int endRow, int n,
  1267. boolean copyRowHeight, boolean resetOriginalRowHeight, boolean moveComments) {
  1268. int s, inc;
  1269. if (n < 0) {
  1270. s = startRow;
  1271. inc = 1;
  1272. } else if (n > 0) {
  1273. s = endRow;
  1274. inc = -1;
  1275. } else {
  1276. // Nothing to do
  1277. return;
  1278. }
  1279. NoteRecord[] noteRecs;
  1280. if (moveComments) {
  1281. noteRecs = _sheet.getNoteRecords();
  1282. } else {
  1283. noteRecs = NoteRecord.EMPTY_ARRAY;
  1284. }
  1285. shiftMerged(startRow, endRow, n, true);
  1286. _sheet.getPageSettings().shiftRowBreaks(startRow, endRow, n);
  1287. for (int rowNum = s; rowNum >= startRow && rowNum <= endRow && rowNum >= 0 && rowNum < 65536; rowNum += inc) {
  1288. HSSFRow row = getRow(rowNum);
  1289. // notify all cells in this row that we are going to shift them,
  1290. // it can throw IllegalStateException if the operation is not allowed, for example,
  1291. // if the row contains cells included in a multi-cell array formula
  1292. if (row != null) notifyRowShifting(row);
  1293. HSSFRow row2Replace = getRow(rowNum + n);
  1294. if (row2Replace == null)
  1295. row2Replace = createRow(rowNum + n);
  1296. // Remove all the old cells from the row we'll
  1297. // be writing too, before we start overwriting
  1298. // any cells. This avoids issues with cells
  1299. // changing type, and records not being correctly
  1300. // overwritten
  1301. row2Replace.removeAllCells();
  1302. // If this row doesn't exist, nothing needs to
  1303. // be done for the now empty destination row
  1304. if (row == null) continue; // Nothing to do for this row
  1305. // Fix up row heights if required
  1306. if (copyRowHeight) {
  1307. row2Replace.setHeight(row.getHeight());
  1308. }
  1309. if (resetOriginalRowHeight) {
  1310. row.setHeight((short) 0xff);
  1311. }
  1312. // Copy each cell from the source row to
  1313. // the destination row
  1314. for (Iterator<Cell> cells = row.cellIterator(); cells.hasNext(); ) {
  1315. HSSFCell cell = (HSSFCell) cells.next();
  1316. row.removeCell(cell);
  1317. CellValueRecordInterface cellRecord = cell.getCellValueRecord();
  1318. cellRecord.setRow(rowNum + n);
  1319. row2Replace.createCellFromRecord(cellRecord);
  1320. _sheet.addValueRecord(rowNum + n, cellRecord);
  1321. HSSFHyperlink link = cell.getHyperlink();
  1322. if (link != null) {
  1323. link.setFirstRow(link.getFirstRow() + n);
  1324. link.setLastRow(link.getLastRow() + n);
  1325. }
  1326. }
  1327. // Now zap all the cells in the source row
  1328. row.removeAllCells();
  1329. // Move comments from the source row to the
  1330. // destination row. Note that comments can
  1331. // exist for cells which are null
  1332. if (moveComments) {
  1333. // This code would get simpler if NoteRecords could be organised by HSSFRow.
  1334. HSSFPatriarch patriarch = createDrawingPatriarch();
  1335. for (int i = patriarch.getChildren().size() - 1; i >= 0; i--) {
  1336. HSSFShape shape = patriarch.getChildren().get(i);
  1337. if (!(shape instanceof HSSFComment)) {
  1338. continue;
  1339. }
  1340. HSSFComment comment = (HSSFComment) shape;
  1341. if (comment.getRow() != rowNum) {
  1342. continue;
  1343. }
  1344. comment.setRow(rowNum + n);
  1345. }
  1346. }
  1347. }
  1348. // Re-compute the first and last rows of the sheet as needed
  1349. if (n > 0) {
  1350. // Rows are moving down
  1351. if (startRow == _firstrow) {
  1352. // Need to walk forward to find the first non-blank row
  1353. _firstrow = Math.max(startRow + n, 0);
  1354. for (int i = startRow + 1; i < startRow + n; i++) {
  1355. if (getRow(i) != null) {
  1356. _firstrow = i;
  1357. break;
  1358. }
  1359. }
  1360. }
  1361. if (endRow + n > _lastrow) {
  1362. _lastrow = Math.min(endRow + n, SpreadsheetVersion.EXCEL97.getLastRowIndex());
  1363. }
  1364. } else {
  1365. // Rows are moving up
  1366. if (startRow + n < _firstrow) {
  1367. _firstrow = Math.max(startRow + n, 0);
  1368. }
  1369. if (endRow == _lastrow) {
  1370. // Need to walk backward to find the last non-blank row
  1371. _lastrow = Math.min(endRow + n, SpreadsheetVersion.EXCEL97.getLastRowIndex());
  1372. for (int i = endRow - 1; i > endRow + n; i++) {
  1373. if (getRow(i) != null) {
  1374. _lastrow = i;
  1375. break;
  1376. }
  1377. }
  1378. }
  1379. }
  1380. // Update any formulas on this sheet that point to
  1381. // rows which have been moved
  1382. int sheetIndex = _workbook.getSheetIndex(this);
  1383. String sheetName = _workbook.getSheetName(sheetIndex);
  1384. short externSheetIndex = _book.checkExternSheet(sheetIndex);
  1385. FormulaShifter shifter = FormulaShifter.createForRowShift(
  1386. externSheetIndex, sheetName, startRow, endRow, n);
  1387. _sheet.updateFormulasAfterCellShift(shifter, externSheetIndex);
  1388. int nSheets = _workbook.getNumberOfSheets();
  1389. for (int i = 0; i < nSheets; i++) {
  1390. InternalSheet otherSheet = _workbook.getSheetAt(i).getSheet();
  1391. if (otherSheet == this._sheet) {
  1392. continue;
  1393. }
  1394. short otherExtSheetIx = _book.checkExternSheet(i);
  1395. otherSheet.updateFormulasAfterCellShift(shifter, otherExtSheetIx);
  1396. }
  1397. _workbook.getWorkbook().updateNamesAfterCellShift(shifter);
  1398. }
  1399. protected void insertChartRecords(List<Record> records) {
  1400. int window2Loc = _sheet.findFirstRecordLocBySid(WindowTwoRecord.sid);
  1401. _sheet.getRecords().addAll(window2Loc, records);
  1402. }
  1403. private void notifyRowShifting(HSSFRow row) {
  1404. String msg = "Row[rownum=" + row.getRowNum() + "] contains cell(s) included in a multi-cell array formula. " +
  1405. "You cannot change part of an array.";
  1406. for (Cell cell : row) {
  1407. HSSFCell hcell = (HSSFCell) cell;
  1408. if (hcell.isPartOfArrayFormulaGroup()) {
  1409. hcell.notifyArrayFormulaChanging(msg);
  1410. }
  1411. }
  1412. }
  1413. /**
  1414. * Creates a split (freezepane). Any existing freezepane or split pane is overwritten.
  1415. * <p/>
  1416. * <p>
  1417. * If both colSplit and rowSplit are zero then the existing freeze pane is removed
  1418. * </p>
  1419. *
  1420. * @param colSplit Horizonatal position of split.
  1421. * @param rowSplit Vertical position of split.
  1422. * @param leftmostColumn Left column visible in right pane.
  1423. * @param topRow Top row visible in bottom pane
  1424. */
  1425. public void createFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow) {
  1426. validateColumn(colSplit);
  1427. validateRow(rowSplit);
  1428. if (leftmostColumn < colSplit)
  1429. throw new IllegalArgumentException("leftmostColumn parameter must not be less than colSplit parameter");
  1430. if (topRow < rowSplit)
  1431. throw new IllegalArgumentException("topRow parameter must not be less than leftmostColumn parameter");
  1432. getSheet().createFreezePane(colSplit, rowSplit, topRow, leftmostColumn);
  1433. }
  1434. /**
  1435. * Creates a split (freezepane). Any existing freezepane or split pane is overwritten.
  1436. * <p/>
  1437. * <p>
  1438. * If both colSplit and rowSplit are zero then the existing freeze pane is removed
  1439. * </p>
  1440. *
  1441. * @param colSplit Horizonatal position of split.
  1442. * @param rowSplit Vertical position of split.
  1443. */
  1444. public void createFreezePane(int colSplit, int rowSplit) {
  1445. createFreezePane(colSplit, rowSplit, colSplit, rowSplit);
  1446. }
  1447. /**
  1448. * Creates a split pane. Any existing freezepane or split pane is overwritten.
  1449. *
  1450. * @param xSplitPos Horizonatal position of split (in 1/20th of a point).
  1451. * @param ySplitPos Vertical position of split (in 1/20th of a point).
  1452. * @param topRow Top row visible in bottom pane
  1453. * @param leftmostColumn Left column visible in right pane.
  1454. * @param activePane Active pane. One of: PANE_LOWER_RIGHT,
  1455. * PANE_UPPER_RIGHT, PANE_LOWER_LEFT, PANE_UPPER_LEFT
  1456. * @see #PANE_LOWER_LEFT
  1457. * @see #PANE_LOWER_RIGHT
  1458. * @see #PANE_UPPER_LEFT
  1459. * @see #PANE_UPPER_RIGHT
  1460. */
  1461. public void createSplitPane(int xSplitPos, int ySplitPos, int leftmostColumn, int topRow, int activePane) {
  1462. getSheet().createSplitPane(xSplitPos, ySplitPos, topRow, leftmostColumn, activePane);
  1463. }
  1464. /**
  1465. * Returns the information regarding the currently configured pane (split or freeze).
  1466. *
  1467. * @return null if no pane configured, or the pane information.
  1468. */
  1469. public PaneInformation getPaneInformation() {
  1470. return getSheet().getPaneInformation();
  1471. }
  1472. /**
  1473. * Sets whether the gridlines are shown in a viewer.
  1474. *
  1475. * @param show whether to show gridlines or not
  1476. */
  1477. public void setDisplayGridlines(boolean show) {
  1478. _sheet.setDisplayGridlines(show);
  1479. }
  1480. /**
  1481. * Returns if gridlines are displayed.
  1482. *
  1483. * @return whether gridlines are displayed
  1484. */
  1485. public boolean isDisplayGridlines() {
  1486. return _sheet.isDisplayGridlines();
  1487. }
  1488. /**
  1489. * Sets whether the formulas are shown in a viewer.
  1490. *
  1491. * @param show whether to show formulas or not
  1492. */
  1493. public void setDisplayFormulas(boolean show) {
  1494. _sheet.setDisplayFormulas(show);
  1495. }
  1496. /**
  1497. * Returns if formulas are displayed.
  1498. *
  1499. * @return whether formulas are displayed
  1500. */
  1501. public boolean isDisplayFormulas() {
  1502. return _sheet.isDisplayFormulas();
  1503. }
  1504. /**
  1505. * Sets whether the RowColHeadings are shown in a viewer.
  1506. *
  1507. * @param show whether to show RowColHeadings or not
  1508. */
  1509. public void setDisplayRowColHeadings(boolean show) {
  1510. _sheet.setDisplayRowColHeadings(show);
  1511. }
  1512. /**
  1513. * Returns if RowColHeadings are displayed.
  1514. *
  1515. * @return whether RowColHeadings are displayed
  1516. */
  1517. public boolean isDisplayRowColHeadings() {
  1518. return _sheet.isDisplayRowColHeadings();
  1519. }
  1520. /**
  1521. * Sets a page break at the indicated row
  1522. * Breaks occur above the specified row and left of the specified column inclusive.
  1523. * <p/>
  1524. * For example, <code>sheet.setColumnBreak(2);</code> breaks the sheet into two parts
  1525. * with columns A,B,C in the first and D,E,... in the second. Simuilar, <code>sheet.setRowBreak(2);</code>
  1526. * breaks the sheet into two parts with first three rows (rownum=1...3) in the first part
  1527. * and rows starting with rownum=4 in the second.
  1528. *
  1529. * @param row the row to break, inclusive
  1530. */
  1531. public void setRowBreak(int row) {
  1532. validateRow(row);
  1533. _sheet.getPageSettings().setRowBreak(row, (short) 0, (short) 255);
  1534. }
  1535. /**
  1536. * @return <code>true</code> if there is a page break at the indicated row
  1537. */
  1538. public boolean isRowBroken(int row) {
  1539. return _sheet.getPageSettings().isRowBroken(row);
  1540. }
  1541. /**
  1542. * Removes the page break at the indicated row
  1543. */
  1544. public void removeRowBreak(int row) {
  1545. _sheet.getPageSettings().removeRowBreak(row);
  1546. }
  1547. /**
  1548. * @return row indexes of all the horizontal page breaks, never <code>null</code>
  1549. */
  1550. public int[] getRowBreaks() {
  1551. //we can probably cache this information, but this should be a sparsely used function
  1552. return _sheet.getPageSettings().getRowBreaks();
  1553. }
  1554. /**
  1555. * @return column indexes of all the vertical page breaks, never <code>null</code>
  1556. */
  1557. public int[] getColumnBreaks() {
  1558. //we can probably cache this information, but this should be a sparsely used function
  1559. return _sheet.getPageSettings().getColumnBreaks();
  1560. }
  1561. /**
  1562. * Sets a page break at the indicated column.
  1563. * Breaks occur above the specified row and left of the specified column inclusive.
  1564. * <p/>
  1565. * For example, <code>sheet.setColumnBreak(2);</code> breaks the sheet into two parts
  1566. * with columns A,B,C in the first and D,E,... in the second. Simuilar, <code>sheet.setRowBreak(2);</code>
  1567. * breaks the sheet into two parts with first three rows (rownum=1...3) in the first part
  1568. * and rows starting with rownum=4 in the second.
  1569. *
  1570. * @param column the column to break, inclusive
  1571. */
  1572. public void setColumnBreak(int column) {
  1573. validateColumn((short) column);
  1574. _sheet.getPageSettings().setColumnBreak((short) column, (short) 0, (short) SpreadsheetVersion.EXCEL97.getLastRowIndex());
  1575. }
  1576. /**
  1577. * Determines if there is a page break at the indicated column
  1578. *
  1579. * @param column FIXME: Document this!
  1580. * @return FIXME: Document this!
  1581. */
  1582. public boolean isColumnBroken(int column) {
  1583. return _sheet.getPageSettings().isColumnBroken(column);
  1584. }
  1585. /**
  1586. * Removes a page break at the indicated column
  1587. *
  1588. * @param column
  1589. */
  1590. public void removeColumnBreak(int column) {
  1591. _sheet.getPageSettings().removeColumnBreak(column);
  1592. }
  1593. /**
  1594. * Runs a bounds check for row numbers
  1595. *
  1596. * @param row
  1597. */
  1598. protected void validateRow(int row) {
  1599. int maxrow = SpreadsheetVersion.EXCEL97.getLastRowIndex();
  1600. if (row > maxrow) throw new IllegalArgumentException("Maximum row number is " + maxrow);
  1601. if (row < 0) throw new IllegalArgumentException("Minumum row number is 0");
  1602. }
  1603. /**
  1604. * Runs a bounds check for column numbers
  1605. *
  1606. * @param column
  1607. */
  1608. protected void validateColumn(int column) {
  1609. int maxcol = SpreadsheetVersion.EXCEL97.getLastColumnIndex();
  1610. if (column > maxcol) throw new IllegalArgumentException("Maximum column number is " + maxcol);
  1611. if (column < 0) throw new IllegalArgumentException("Minimum column number is 0");
  1612. }
  1613. /**
  1614. * Aggregates the drawing records and dumps the escher record hierarchy
  1615. * to the standard output.
  1616. */
  1617. public void dumpDrawingRecords(boolean fat) {
  1618. _sheet.aggregateDrawingRecords(_book.getDrawingManager(), false);
  1619. EscherAggregate r = (EscherAggregate) getSheet().findFirstRecordBySid(EscherAggregate.sid);
  1620. List<EscherRecord> escherRecords = r.getEscherRecords();
  1621. PrintWriter w = new PrintWriter(System.out);
  1622. for (Iterator<EscherRecord> iterator = escherRecords.iterator(); iterator.hasNext(); ) {
  1623. EscherRecord escherRecord = iterator.next();
  1624. if (fat) {
  1625. System.out.println(escherRecord.toString());
  1626. } else {
  1627. escherRecord.display(w, 0);
  1628. }
  1629. }
  1630. w.flush();
  1631. }
  1632. /**
  1633. * Returns the agregate escher records for this sheet,
  1634. * it there is one.
  1635. */
  1636. public EscherAggregate getDrawingEscherAggregate() {
  1637. _book.findDrawingGroup();
  1638. // If there's now no drawing manager, then there's
  1639. // no drawing escher records on the workbook
  1640. if (_book.getDrawingManager() == null) {
  1641. return null;
  1642. }
  1643. int found = _sheet.aggregateDrawingRecords(
  1644. _book.getDrawingManager(), false
  1645. );
  1646. if (found == -1) {
  1647. // Workbook has drawing stuff, but this sheet doesn't
  1648. return null;
  1649. }
  1650. // Grab our aggregate record, and wire it up
  1651. EscherAggregate agg = (EscherAggregate) _sheet.findFirstRecordBySid(EscherAggregate.sid);
  1652. return agg;
  1653. }
  1654. /**
  1655. * This will hold any graphics or charts for the sheet.
  1656. *
  1657. * @return the top-level drawing patriarch, if there is one, else returns null
  1658. */
  1659. public HSSFPatriarch getDrawingPatriarch() {
  1660. _patriarch = getPatriarch(false);
  1661. return _patriarch;
  1662. }
  1663. /**
  1664. * Creates the top-level drawing patriarch.
  1665. * <p>This may then be used to add graphics or charts.</p>
  1666. * <p>Note that this will normally have the effect of removing
  1667. * any existing drawings on this sheet.</p>
  1668. *
  1669. * @return The new patriarch.
  1670. */
  1671. public HSSFPatriarch createDrawingPatriarch() {
  1672. _patriarch = getPatriarch(true);
  1673. return _patriarch;
  1674. }
  1675. private HSSFPatriarch getPatriarch(boolean createIfMissing) {
  1676. HSSFPatriarch patriarch = null;
  1677. if (_patriarch != null) {
  1678. return _patriarch;
  1679. }
  1680. DrawingManager2 dm = _book.findDrawingGroup();
  1681. if (null == dm) {
  1682. if (!createIfMissing) {
  1683. return null;
  1684. } else {
  1685. _book.createDrawingGroup();
  1686. dm = _book.getDrawingManager();
  1687. }
  1688. }
  1689. EscherAggregate agg = (EscherAggregate) _sheet.findFirstRecordBySid(EscherAggregate.sid);
  1690. if (null == agg) {
  1691. int pos = _sheet.aggregateDrawingRecords(dm, false);
  1692. if (-1 == pos) {
  1693. if (createIfMissing) {
  1694. pos = _sheet.aggregateDrawingRecords(dm, true);
  1695. agg = (EscherAggregate) _sheet.getRecords().get(pos);
  1696. patriarch = new HSSFPatriarch(this, agg);
  1697. patriarch.afterCreate();
  1698. return patriarch;
  1699. } else {
  1700. return null;
  1701. }
  1702. }
  1703. agg = (EscherAggregate) _sheet.getRecords().get(pos);
  1704. }
  1705. return new HSSFPatriarch(this, agg);
  1706. }
  1707. /**
  1708. * @deprecated (Sep 2008) use {@link #setColumnGroupCollapsed(int, boolean)}
  1709. */
  1710. public void setColumnGroupCollapsed(short columnNumber, boolean collapsed) {
  1711. setColumnGroupCollapsed(columnNumber & 0xFFFF, collapsed);
  1712. }
  1713. /**
  1714. * @deprecated (Sep 2008) use {@link #groupColumn(int, int)}
  1715. */
  1716. public void groupColumn(short fromColumn, short toColumn) {
  1717. groupColumn(fromColumn & 0xFFFF, toColumn & 0xFFFF);
  1718. }
  1719. /**
  1720. * @deprecated (Sep 2008) use {@link #ungroupColumn(int, int)}
  1721. */
  1722. public void ungroupColumn(short fromColumn, short toColumn) {
  1723. ungroupColumn(fromColumn & 0xFFFF, toColumn & 0xFFFF);
  1724. }
  1725. /**
  1726. * Expands or collapses a column group.
  1727. *
  1728. * @param columnNumber One of the columns in the group.
  1729. * @param collapsed true = collapse group, false = expand group.
  1730. */
  1731. public void setColumnGroupCollapsed(int columnNumber, boolean collapsed) {
  1732. _sheet.setColumnGroupCollapsed(columnNumber, collapsed);
  1733. }
  1734. /**
  1735. * Create an outline for the provided column range.
  1736. *
  1737. * @param fromColumn beginning of the column range.
  1738. * @param toColumn end of the column range.
  1739. */
  1740. public void groupColumn(int fromColumn, int toColumn) {
  1741. _sheet.groupColumnRange(fromColumn, toColumn, true);
  1742. }
  1743. public void ungroupColumn(int fromColumn, int toColumn) {
  1744. _sheet.groupColumnRange(fromColumn, toColumn, false);
  1745. }
  1746. /**
  1747. * Tie a range of cell together so that they can be collapsed or expanded
  1748. *
  1749. * @param fromRow start row (0-based)
  1750. * @param toRow end row (0-based)
  1751. */
  1752. public void groupRow(int fromRow, int toRow) {
  1753. _sheet.groupRowRange(fromRow, toRow, true);
  1754. }
  1755. public void ungroupRow(int fromRow, int toRow) {
  1756. _sheet.groupRowRange(fromRow, toRow, false);
  1757. }
  1758. public void setRowGroupCollapsed(int rowIndex, boolean collapse) {
  1759. if (collapse) {
  1760. _sheet.getRowsAggregate().collapseRow(rowIndex);
  1761. } else {
  1762. _sheet.getRowsAggregate().expandRow(rowIndex);
  1763. }
  1764. }
  1765. /**
  1766. * Sets the default column style for a given column. POI will only apply this style to new cells added to the sheet.
  1767. *
  1768. * @param column the column index
  1769. * @param style the style to set
  1770. */
  1771. public void setDefaultColumnStyle(int column, CellStyle style) {
  1772. _sheet.setDefaultColumnStyle(column, ((HSSFCellStyle) style).getIndex());
  1773. }
  1774. /**
  1775. * Adjusts the column width to fit the contents.
  1776. * <p/>
  1777. * This process can be relatively slow on large sheets, so this should
  1778. * normally only be called once per column, at the end of your
  1779. * processing.
  1780. *
  1781. * @param column the column index
  1782. */
  1783. public void autoSizeColumn(int column) {
  1784. autoSizeColumn(column, false);
  1785. }
  1786. /**
  1787. * Adjusts the column width to fit the contents.
  1788. * <p/>
  1789. * This process can be relatively slow on large sheets, so this should
  1790. * normally only be called once per column, at the end of your
  1791. * processing.
  1792. * <p/>
  1793. * You can specify whether the content of merged cells should be considered or ignored.
  1794. * Default is to ignore merged cells.
  1795. *
  1796. * @param column the column index
  1797. * @param useMergedCells whether to use the contents of merged cells when calculating the width of the column
  1798. */
  1799. public void autoSizeColumn(int column, boolean useMergedCells) {
  1800. double width = SheetUtil.getColumnWidth(this, column, useMergedCells);
  1801. if (width != -1) {
  1802. width *= 256;
  1803. int maxColumnWidth = 255 * 256; // The maximum column width for an individual cell is 255 characters
  1804. if (width > maxColumnWidth) {
  1805. width = maxColumnWidth;
  1806. }
  1807. setColumnWidth(column, (int) (width));
  1808. }
  1809. }
  1810. /**
  1811. * Returns cell comment for the specified row and column
  1812. *
  1813. * @return cell comment or <code>null</code> if not found
  1814. */
  1815. public HSSFComment getCellComment(int row, int column) {
  1816. return findCellComment(row, column);
  1817. }
  1818. public HSSFSheetConditionalFormatting getSheetConditionalFormatting() {
  1819. return new HSSFSheetConditionalFormatting(this);
  1820. }
  1821. /**
  1822. * Returns the name of this sheet
  1823. *
  1824. * @return the name of this sheet
  1825. */
  1826. public String getSheetName() {
  1827. HSSFWorkbook wb = getWorkbook();
  1828. int idx = wb.getSheetIndex(this);
  1829. return wb.getSheetName(idx);
  1830. }
  1831. /**
  1832. * Also creates cells if they don't exist
  1833. */
  1834. private CellRange<HSSFCell> getCellRange(CellRangeAddress range) {
  1835. int firstRow = range.getFirstRow();
  1836. int firstColumn = range.getFirstColumn();
  1837. int lastRow = range.getLastRow();
  1838. int lastColumn = range.getLastColumn();
  1839. int height = lastRow - firstRow + 1;
  1840. int width = lastColumn - firstColumn + 1;
  1841. List<HSSFCell> temp = new ArrayList<HSSFCell>(height * width);
  1842. for (int rowIn = firstRow; rowIn <= lastRow; rowIn++) {
  1843. for (int colIn = firstColumn; colIn <= lastColumn; colIn++) {
  1844. HSSFRow row = getRow(rowIn);
  1845. if (row == null) {
  1846. row = createRow(rowIn);
  1847. }
  1848. HSSFCell cell = row.getCell(colIn);
  1849. if (cell == null) {
  1850. cell = row.createCell(colIn);
  1851. }
  1852. temp.add(cell);
  1853. }
  1854. }
  1855. return SSCellRange.create(firstRow, firstColumn, height, width, temp, HSSFCell.class);
  1856. }
  1857. public CellRange<HSSFCell> setArrayFormula(String formula, CellRangeAddress range) {
  1858. // make sure the formula parses OK first
  1859. int sheetIndex = _workbook.getSheetIndex(this);
  1860. Ptg[] ptgs = HSSFFormulaParser.parse(formula, _workbook, FormulaType.ARRAY, sheetIndex);
  1861. CellRange<HSSFCell> cells = getCellRange(range);
  1862. for (HSSFCell c : cells) {
  1863. c.setCellArrayFormula(range);
  1864. }
  1865. HSSFCell mainArrayFormulaCell = cells.getTopLeftCell();
  1866. FormulaRecordAggregate agg = (FormulaRecordAggregate) mainArrayFormulaCell.getCellValueRecord();
  1867. agg.setArrayFormula(range, ptgs);
  1868. return cells;
  1869. }
  1870. public CellRange<HSSFCell> removeArrayFormula(Cell cell) {
  1871. if (cell.getSheet() != this) {
  1872. throw new IllegalArgumentException("Specified cell does not belong to this sheet.");
  1873. }
  1874. CellValueRecordInterface rec = ((HSSFCell) cell).getCellValueRecord();
  1875. if (!(rec instanceof FormulaRecordAggregate)) {
  1876. String ref = new CellReference(cell).formatAsString();
  1877. throw new IllegalArgumentException("Cell " + ref + " is not part of an array formula.");
  1878. }
  1879. FormulaRecordAggregate fra = (FormulaRecordAggregate) rec;
  1880. CellRangeAddress range = fra.removeArrayFormula(cell.getRowIndex(), cell.getColumnIndex());
  1881. CellRange<HSSFCell> result = getCellRange(range);
  1882. // clear all cells in the range
  1883. for (Cell c : result) {
  1884. c.setCellType(Cell.CELL_TYPE_BLANK);
  1885. }
  1886. return result;
  1887. }
  1888. public DataValidationHelper getDataValidationHelper() {
  1889. return new HSSFDataValidationHelper(this);
  1890. }
  1891. public HSSFAutoFilter setAutoFilter(CellRangeAddress range) {
  1892. InternalWorkbook workbook = _workbook.getWorkbook();
  1893. int sheetIndex = _workbook.getSheetIndex(this);
  1894. NameRecord name = workbook.getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, sheetIndex + 1);
  1895. if (name == null) {
  1896. name = workbook.createBuiltInName(NameRecord.BUILTIN_FILTER_DB, sheetIndex + 1);
  1897. }
  1898. int firstRow = range.getFirstRow();
  1899. // if row was not given when constructing the range...
  1900. if(firstRow == -1) {
  1901. firstRow = 0;
  1902. }
  1903. // The built-in name must consist of a single Area3d Ptg.
  1904. Area3DPtg ptg = new Area3DPtg(firstRow, range.getLastRow(),
  1905. range.getFirstColumn(), range.getLastColumn(),
  1906. false, false, false, false, sheetIndex);
  1907. name.setNameDefinition(new Ptg[]{ptg});
  1908. AutoFilterInfoRecord r = new AutoFilterInfoRecord();
  1909. // the number of columns that have AutoFilter enabled.
  1910. int numcols = 1 + range.getLastColumn() - range.getFirstColumn();
  1911. r.setNumEntries((short) numcols);
  1912. int idx = _sheet.findFirstRecordLocBySid(DimensionsRecord.sid);
  1913. _sheet.getRecords().add(idx, r);
  1914. //create a combobox control for each column
  1915. HSSFPatriarch p = createDrawingPatriarch();
  1916. for (int col = range.getFirstColumn(); col <= range.getLastColumn(); col++) {
  1917. p.createComboBox(new HSSFClientAnchor(0, 0, 0, 0,
  1918. (short) col, firstRow, (short) (col + 1), firstRow + 1));
  1919. }
  1920. return new HSSFAutoFilter(this);
  1921. }
  1922. protected HSSFComment findCellComment(int row, int column) {
  1923. HSSFPatriarch patriarch = getDrawingPatriarch();
  1924. if (null == patriarch) {
  1925. patriarch = createDrawingPatriarch();
  1926. }
  1927. return lookForComment(patriarch, row, column);
  1928. }
  1929. private HSSFComment lookForComment(HSSFShapeContainer container, int row, int column) {
  1930. for (Object object : container.getChildren()) {
  1931. HSSFShape shape = (HSSFShape) object;
  1932. if (shape instanceof HSSFShapeGroup) {
  1933. HSSFShape res = lookForComment((HSSFShapeContainer) shape, row, column);
  1934. if (null != res) {
  1935. return (HSSFComment) res;
  1936. }
  1937. continue;
  1938. }
  1939. if (shape instanceof HSSFComment) {
  1940. HSSFComment comment = (HSSFComment) shape;
  1941. if (comment.hasPosition() && comment.getColumn() == column && comment.getRow() == row) {
  1942. return comment;
  1943. }
  1944. }
  1945. }
  1946. return null;
  1947. }
  1948. public CellRangeAddress getRepeatingRows() {
  1949. return getRepeatingRowsOrColums(true);
  1950. }
  1951. public CellRangeAddress getRepeatingColumns() {
  1952. return getRepeatingRowsOrColums(false);
  1953. }
  1954. public void setRepeatingRows(CellRangeAddress rowRangeRef) {
  1955. CellRangeAddress columnRangeRef = getRepeatingColumns();
  1956. setRepeatingRowsAndColumns(rowRangeRef, columnRangeRef);
  1957. }
  1958. public void setRepeatingColumns(CellRangeAddress columnRangeRef) {
  1959. CellRangeAddress rowRangeRef = getRepeatingRows();
  1960. setRepeatingRowsAndColumns(rowRangeRef, columnRangeRef);
  1961. }
  1962. private void setRepeatingRowsAndColumns(
  1963. CellRangeAddress rowDef, CellRangeAddress colDef) {
  1964. int sheetIndex = _workbook.getSheetIndex(this);
  1965. int maxRowIndex = SpreadsheetVersion.EXCEL97.getLastRowIndex();
  1966. int maxColIndex = SpreadsheetVersion.EXCEL97.getLastColumnIndex();
  1967. int col1 = -1;
  1968. int col2 = -1;
  1969. int row1 = -1;
  1970. int row2 = -1;
  1971. if (rowDef != null) {
  1972. row1 = rowDef.getFirstRow();
  1973. row2 = rowDef.getLastRow();
  1974. if ((row1 == -1 && row2 != -1) || (row1 > row2)
  1975. || (row1 < 0 || row1 > maxRowIndex)
  1976. || (row2 < 0 || row2 > maxRowIndex)) {
  1977. throw new IllegalArgumentException("Invalid row range specification");
  1978. }
  1979. }
  1980. if (colDef != null) {
  1981. col1 = colDef.getFirstColumn();
  1982. col2 = colDef.getLastColumn();
  1983. if ((col1 == -1 && col2 != -1) || (col1 > col2)
  1984. || (col1 < 0 || col1 > maxColIndex)
  1985. || (col2 < 0 || col2 > maxColIndex)) {
  1986. throw new IllegalArgumentException("Invalid column range specification");
  1987. }
  1988. }
  1989. short externSheetIndex =
  1990. _workbook.getWorkbook().checkExternSheet(sheetIndex);
  1991. boolean setBoth = rowDef != null && colDef != null;
  1992. boolean removeAll = rowDef == null && colDef == null;
  1993. HSSFName name = _workbook.getBuiltInName(
  1994. NameRecord.BUILTIN_PRINT_TITLE, sheetIndex);
  1995. if (removeAll) {
  1996. if (name != null) {
  1997. _workbook.removeName(name);
  1998. }
  1999. return;
  2000. }
  2001. if (name == null) {
  2002. name = _workbook.createBuiltInName(
  2003. NameRecord.BUILTIN_PRINT_TITLE, sheetIndex);
  2004. }
  2005. List<Ptg> ptgList = new ArrayList<Ptg>();
  2006. if (setBoth) {
  2007. final int exprsSize = 2 * 11 + 1; // 2 * Area3DPtg.SIZE + UnionPtg.SIZE
  2008. ptgList.add(new MemFuncPtg(exprsSize));
  2009. }
  2010. if (colDef != null) {
  2011. Area3DPtg colArea = new Area3DPtg(0, maxRowIndex, col1, col2,
  2012. false, false, false, false, externSheetIndex);
  2013. ptgList.add(colArea);
  2014. }
  2015. if (rowDef != null) {
  2016. Area3DPtg rowArea = new Area3DPtg(row1, row2, 0, maxColIndex,
  2017. false, false, false, false, externSheetIndex);
  2018. ptgList.add(rowArea);
  2019. }
  2020. if (setBoth) {
  2021. ptgList.add(UnionPtg.instance);
  2022. }
  2023. Ptg[] ptgs = new Ptg[ptgList.size()];
  2024. ptgList.toArray(ptgs);
  2025. name.setNameDefinition(ptgs);
  2026. HSSFPrintSetup printSetup = getPrintSetup();
  2027. printSetup.setValidSettings(false);
  2028. setActive(true);
  2029. }
  2030. private CellRangeAddress getRepeatingRowsOrColums(boolean rows) {
  2031. NameRecord rec = getBuiltinNameRecord(NameRecord.BUILTIN_PRINT_TITLE);
  2032. if (rec == null) {
  2033. return null;
  2034. }
  2035. Ptg[] nameDefinition = rec.getNameDefinition();
  2036. if (nameDefinition == null) {
  2037. return null;
  2038. }
  2039. int maxRowIndex = SpreadsheetVersion.EXCEL97.getLastRowIndex();
  2040. int maxColIndex = SpreadsheetVersion.EXCEL97.getLastColumnIndex();
  2041. for (Ptg ptg : nameDefinition) {
  2042. if (ptg instanceof Area3DPtg) {
  2043. Area3DPtg areaPtg = (Area3DPtg) ptg;
  2044. if (areaPtg.getFirstColumn() == 0
  2045. && areaPtg.getLastColumn() == maxColIndex) {
  2046. if (rows) {
  2047. CellRangeAddress rowRange = new CellRangeAddress(
  2048. areaPtg.getFirstRow(), areaPtg.getLastRow(), -1, -1);
  2049. return rowRange;
  2050. }
  2051. } else if (areaPtg.getFirstRow() == 0
  2052. && areaPtg.getLastRow() == maxRowIndex) {
  2053. if (!rows) {
  2054. CellRangeAddress columnRange = new CellRangeAddress(-1, -1,
  2055. areaPtg.getFirstColumn(), areaPtg.getLastColumn());
  2056. return columnRange;
  2057. }
  2058. }
  2059. }
  2060. }
  2061. return null;
  2062. }
  2063. private NameRecord getBuiltinNameRecord(byte builtinCode) {
  2064. int sheetIndex = _workbook.getSheetIndex(this);
  2065. int recIndex =
  2066. _workbook.findExistingBuiltinNameRecordIdx(sheetIndex, builtinCode);
  2067. if (recIndex == -1) {
  2068. return null;
  2069. }
  2070. return _workbook.getNameRecord(recIndex);
  2071. }
  2072. /**
  2073. * Returns the column outline level. Increased as you
  2074. * put it into more groups (outlines), reduced as
  2075. * you take it out of them.
  2076. */
  2077. public int getColumnOutlineLevel(int columnIndex) {
  2078. return _sheet.getColumnOutlineLevel(columnIndex);
  2079. }
  2080. }