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.

HSSFWorkbook.java 64KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811
  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.ByteArrayInputStream;
  17. import java.io.FileNotFoundException;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.OutputStream;
  21. import java.io.PrintWriter;
  22. import java.util.ArrayList;
  23. import java.util.Hashtable;
  24. import java.util.Iterator;
  25. import java.util.List;
  26. import java.util.regex.Pattern;
  27. import org.apache.poi.POIDocument;
  28. import org.apache.poi.ddf.EscherBSERecord;
  29. import org.apache.poi.ddf.EscherBitmapBlip;
  30. import org.apache.poi.ddf.EscherBlipRecord;
  31. import org.apache.poi.ddf.EscherRecord;
  32. import org.apache.poi.hssf.OldExcelFormatException;
  33. import org.apache.poi.hssf.model.HSSFFormulaParser;
  34. import org.apache.poi.hssf.model.InternalSheet;
  35. import org.apache.poi.hssf.model.InternalWorkbook;
  36. import org.apache.poi.hssf.model.RecordStream;
  37. import org.apache.poi.hssf.model.DrawingManager2;
  38. import org.apache.poi.hssf.record.*;
  39. import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor;
  40. import org.apache.poi.hssf.record.common.UnicodeString;
  41. import org.apache.poi.hssf.util.CellReference;
  42. import org.apache.poi.poifs.filesystem.DirectoryNode;
  43. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  44. import org.apache.poi.ss.formula.FormulaShifter;
  45. import org.apache.poi.ss.formula.FormulaType;
  46. import org.apache.poi.ss.formula.SheetNameFormatter;
  47. import org.apache.poi.ss.formula.ptg.Area3DPtg;
  48. import org.apache.poi.ss.formula.ptg.MemFuncPtg;
  49. import org.apache.poi.ss.formula.ptg.Ptg;
  50. import org.apache.poi.ss.formula.ptg.UnionPtg;
  51. import org.apache.poi.ss.formula.udf.AggregatingUDFFinder;
  52. import org.apache.poi.ss.formula.udf.UDFFinder;
  53. import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
  54. import org.apache.poi.ss.util.WorkbookUtil;
  55. import org.apache.poi.util.POILogFactory;
  56. import org.apache.poi.util.POILogger;
  57. import org.apache.commons.codec.digest.DigestUtils;
  58. /**
  59. * High level representation of a workbook. This is the first object most users
  60. * will construct whether they are reading or writing a workbook. It is also the
  61. * top level object for creating new sheets/etc.
  62. *
  63. * @see org.apache.poi.hssf.model.InternalWorkbook
  64. * @see org.apache.poi.hssf.usermodel.HSSFSheet
  65. * @author Andrew C. Oliver (acoliver at apache dot org)
  66. * @author Glen Stampoultzis (glens at apache.org)
  67. * @author Shawn Laubach (slaubach at apache dot org)
  68. */
  69. public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss.usermodel.Workbook {
  70. private static final Pattern COMMA_PATTERN = Pattern.compile(",");
  71. private static final int MAX_ROW = 0xFFFF;
  72. private static final int MAX_COLUMN = (short)0x00FF;
  73. /**
  74. * The maximum number of cell styles in a .xls workbook.
  75. * The 'official' limit is 4,000, but POI allows a slightly larger number.
  76. * This extra delta takes into account built-in styles that are automatically
  77. * created for new workbooks
  78. *
  79. * See http://office.microsoft.com/en-us/excel-help/excel-specifications-and-limits-HP005199291.aspx
  80. */
  81. private static final int MAX_STYLES = 4030;
  82. private static final int DEBUG = POILogger.DEBUG;
  83. /**
  84. * used for compile-time performance/memory optimization. This determines the
  85. * initial capacity for the sheet collection. Its currently set to 3.
  86. * Changing it in this release will decrease performance
  87. * since you're never allowed to have more or less than three sheets!
  88. */
  89. public final static int INITIAL_CAPACITY = 3;
  90. /**
  91. * this is the reference to the low level Workbook object
  92. */
  93. private InternalWorkbook workbook;
  94. /**
  95. * this holds the HSSFSheet objects attached to this workbook
  96. */
  97. protected List<HSSFSheet> _sheets;
  98. /**
  99. * this holds the HSSFName objects attached to this workbook
  100. */
  101. private ArrayList<HSSFName> names;
  102. /**
  103. * this holds the HSSFFont objects attached to this workbook.
  104. * We only create these from the low level records as required.
  105. */
  106. private Hashtable fonts;
  107. /**
  108. * holds whether or not to preserve other nodes in the POIFS. Used
  109. * for macros and embedded objects.
  110. */
  111. private boolean preserveNodes;
  112. /**
  113. * Used to keep track of the data formatter so that all
  114. * createDataFormatter calls return the same one for a given
  115. * book. This ensures that updates from one places is visible
  116. * someplace else.
  117. */
  118. private HSSFDataFormat formatter;
  119. /**
  120. * The policy to apply in the event of missing or
  121. * blank cells when fetching from a row.
  122. * See {@link MissingCellPolicy}
  123. */
  124. private MissingCellPolicy missingCellPolicy = HSSFRow.RETURN_NULL_AND_BLANK;
  125. private static POILogger log = POILogFactory.getLogger(HSSFWorkbook.class);
  126. /**
  127. * The locator of user-defined functions.
  128. * By default includes functions from the Excel Analysis Toolpack
  129. */
  130. private UDFFinder _udfFinder = UDFFinder.DEFAULT;
  131. public static HSSFWorkbook create(InternalWorkbook book) {
  132. return new HSSFWorkbook(book);
  133. }
  134. /**
  135. * Creates new HSSFWorkbook from scratch (start here!)
  136. *
  137. */
  138. public HSSFWorkbook() {
  139. this(InternalWorkbook.createWorkbook());
  140. }
  141. private HSSFWorkbook(InternalWorkbook book) {
  142. super((DirectoryNode)null);
  143. workbook = book;
  144. _sheets = new ArrayList<HSSFSheet>(INITIAL_CAPACITY);
  145. names = new ArrayList<HSSFName>(INITIAL_CAPACITY);
  146. }
  147. public HSSFWorkbook(POIFSFileSystem fs) throws IOException {
  148. this(fs,true);
  149. }
  150. /**
  151. * given a POI POIFSFileSystem object, read in its Workbook and populate the high and
  152. * low level models. If you're reading in a workbook...start here.
  153. *
  154. * @param fs the POI filesystem that contains the Workbook stream.
  155. * @param preserveNodes whether to preseve other nodes, such as
  156. * macros. This takes more memory, so only say yes if you
  157. * need to. If set, will store all of the POIFSFileSystem
  158. * in memory
  159. * @see org.apache.poi.poifs.filesystem.POIFSFileSystem
  160. * @exception IOException if the stream cannot be read
  161. */
  162. public HSSFWorkbook(POIFSFileSystem fs, boolean preserveNodes)
  163. throws IOException
  164. {
  165. this(fs.getRoot(), fs, preserveNodes);
  166. }
  167. /**
  168. * Normally, the Workbook will be in a POIFS Stream
  169. * called "Workbook". However, some weird XLS generators use "WORKBOOK"
  170. */
  171. private static final String[] WORKBOOK_DIR_ENTRY_NAMES = {
  172. "Workbook", // as per BIFF8 spec
  173. "WORKBOOK",
  174. };
  175. private static String getWorkbookDirEntryName(DirectoryNode directory) {
  176. String[] potentialNames = WORKBOOK_DIR_ENTRY_NAMES;
  177. for (int i = 0; i < potentialNames.length; i++) {
  178. String wbName = potentialNames[i];
  179. try {
  180. directory.getEntry(wbName);
  181. return wbName;
  182. } catch (FileNotFoundException e) {
  183. // continue - to try other options
  184. }
  185. }
  186. // check for previous version of file format
  187. try {
  188. directory.getEntry("Book");
  189. throw new OldExcelFormatException("The supplied spreadsheet seems to be Excel 5.0/7.0 (BIFF5) format. "
  190. + "POI only supports BIFF8 format (from Excel versions 97/2000/XP/2003)");
  191. } catch (FileNotFoundException e) {
  192. // fall through
  193. }
  194. throw new IllegalArgumentException("The supplied POIFSFileSystem does not contain a BIFF8 'Workbook' entry. "
  195. + "Is it really an excel file?");
  196. }
  197. /**
  198. * given a POI POIFSFileSystem object, and a specific directory
  199. * within it, read in its Workbook and populate the high and
  200. * low level models. If you're reading in a workbook...start here.
  201. *
  202. * @param directory the POI filesystem directory to process from
  203. * @param fs the POI filesystem that contains the Workbook stream.
  204. * @param preserveNodes whether to preseve other nodes, such as
  205. * macros. This takes more memory, so only say yes if you
  206. * need to. If set, will store all of the POIFSFileSystem
  207. * in memory
  208. * @see org.apache.poi.poifs.filesystem.POIFSFileSystem
  209. * @exception IOException if the stream cannot be read
  210. */
  211. public HSSFWorkbook(DirectoryNode directory, POIFSFileSystem fs, boolean preserveNodes)
  212. throws IOException
  213. {
  214. this(directory, preserveNodes);
  215. }
  216. /**
  217. * given a POI POIFSFileSystem object, and a specific directory
  218. * within it, read in its Workbook and populate the high and
  219. * low level models. If you're reading in a workbook...start here.
  220. *
  221. * @param directory the POI filesystem directory to process from
  222. * @param preserveNodes whether to preseve other nodes, such as
  223. * macros. This takes more memory, so only say yes if you
  224. * need to. If set, will store all of the POIFSFileSystem
  225. * in memory
  226. * @see org.apache.poi.poifs.filesystem.POIFSFileSystem
  227. * @exception IOException if the stream cannot be read
  228. */
  229. public HSSFWorkbook(DirectoryNode directory, boolean preserveNodes)
  230. throws IOException
  231. {
  232. super(directory);
  233. String workbookName = getWorkbookDirEntryName(directory);
  234. this.preserveNodes = preserveNodes;
  235. // If we're not preserving nodes, don't track the
  236. // POIFS any more
  237. if(! preserveNodes) {
  238. this.directory = null;
  239. }
  240. _sheets = new ArrayList<HSSFSheet>(INITIAL_CAPACITY);
  241. names = new ArrayList<HSSFName>(INITIAL_CAPACITY);
  242. // Grab the data from the workbook stream, however
  243. // it happens to be spelled.
  244. InputStream stream = directory.createDocumentInputStream(workbookName);
  245. List<Record> records = RecordFactory.createRecords(stream);
  246. workbook = InternalWorkbook.createWorkbook(records);
  247. setPropertiesFromWorkbook(workbook);
  248. int recOffset = workbook.getNumRecords();
  249. int sheetNum = 0;
  250. // convert all LabelRecord records to LabelSSTRecord
  251. convertLabelRecords(records, recOffset);
  252. RecordStream rs = new RecordStream(records, recOffset);
  253. while (rs.hasNext()) {
  254. InternalSheet sheet = InternalSheet.createSheet(rs);
  255. _sheets.add(new HSSFSheet(this, sheet));
  256. }
  257. for (int i = 0 ; i < workbook.getNumNames() ; ++i){
  258. NameRecord nameRecord = workbook.getNameRecord(i);
  259. HSSFName name = new HSSFName(this, nameRecord, workbook.getNameCommentRecord(nameRecord));
  260. names.add(name);
  261. }
  262. }
  263. public HSSFWorkbook(InputStream s) throws IOException {
  264. this(s,true);
  265. }
  266. /**
  267. * Companion to HSSFWorkbook(POIFSFileSystem), this constructs the POI filesystem around your
  268. * inputstream.
  269. *
  270. * @param s the POI filesystem that contains the Workbook stream.
  271. * @param preserveNodes whether to preseve other nodes, such as
  272. * macros. This takes more memory, so only say yes if you
  273. * need to.
  274. * @see org.apache.poi.poifs.filesystem.POIFSFileSystem
  275. * @see #HSSFWorkbook(POIFSFileSystem)
  276. * @exception IOException if the stream cannot be read
  277. */
  278. public HSSFWorkbook(InputStream s, boolean preserveNodes)
  279. throws IOException
  280. {
  281. this(new POIFSFileSystem(s), preserveNodes);
  282. }
  283. /**
  284. * used internally to set the workbook properties.
  285. */
  286. private void setPropertiesFromWorkbook(InternalWorkbook book)
  287. {
  288. this.workbook = book;
  289. // none currently
  290. }
  291. /**
  292. * This is basically a kludge to deal with the now obsolete Label records. If
  293. * you have to read in a sheet that contains Label records, be aware that the rest
  294. * of the API doesn't deal with them, the low level structure only provides read-only
  295. * semi-immutable structures (the sets are there for interface conformance with NO
  296. * impelmentation). In short, you need to call this function passing it a reference
  297. * to the Workbook object. All labels will be converted to LabelSST records and their
  298. * contained strings will be written to the Shared String tabel (SSTRecord) within
  299. * the Workbook.
  300. *
  301. * @param records a collection of sheet's records.
  302. * @param offset the offset to search at
  303. * @see org.apache.poi.hssf.record.LabelRecord
  304. * @see org.apache.poi.hssf.record.LabelSSTRecord
  305. * @see org.apache.poi.hssf.record.SSTRecord
  306. */
  307. private void convertLabelRecords(List records, int offset)
  308. {
  309. if (log.check( POILogger.DEBUG ))
  310. log.log(POILogger.DEBUG, "convertLabelRecords called");
  311. for (int k = offset; k < records.size(); k++)
  312. {
  313. Record rec = ( Record ) records.get(k);
  314. if (rec.getSid() == LabelRecord.sid)
  315. {
  316. LabelRecord oldrec = ( LabelRecord ) rec;
  317. records.remove(k);
  318. LabelSSTRecord newrec = new LabelSSTRecord();
  319. int stringid =
  320. workbook.addSSTString(new UnicodeString(oldrec.getValue()));
  321. newrec.setRow(oldrec.getRow());
  322. newrec.setColumn(oldrec.getColumn());
  323. newrec.setXFIndex(oldrec.getXFIndex());
  324. newrec.setSSTIndex(stringid);
  325. records.add(k, newrec);
  326. }
  327. }
  328. if (log.check( POILogger.DEBUG ))
  329. log.log(POILogger.DEBUG, "convertLabelRecords exit");
  330. }
  331. /**
  332. * Retrieves the current policy on what to do when
  333. * getting missing or blank cells from a row.
  334. * The default is to return blank and null cells.
  335. * {@link MissingCellPolicy}
  336. */
  337. public MissingCellPolicy getMissingCellPolicy() {
  338. return missingCellPolicy;
  339. }
  340. /**
  341. * Sets the policy on what to do when
  342. * getting missing or blank cells from a row.
  343. * This will then apply to all calls to
  344. * {@link HSSFRow#getCell(int)}}. See
  345. * {@link MissingCellPolicy}.
  346. * Note that this has no effect on any
  347. * iterators, only on when fetching Cells
  348. * by their column index.
  349. */
  350. public void setMissingCellPolicy(MissingCellPolicy missingCellPolicy) {
  351. this.missingCellPolicy = missingCellPolicy;
  352. }
  353. /**
  354. * sets the order of appearance for a given sheet.
  355. *
  356. * @param sheetname the name of the sheet to reorder
  357. * @param pos the position that we want to insert the sheet into (0 based)
  358. */
  359. public void setSheetOrder(String sheetname, int pos ) {
  360. int oldSheetIndex = getSheetIndex(sheetname);
  361. _sheets.add(pos,_sheets.remove(oldSheetIndex));
  362. workbook.setSheetOrder(sheetname, pos);
  363. FormulaShifter shifter = FormulaShifter.createForSheetShift(oldSheetIndex, pos);
  364. for (HSSFSheet sheet : _sheets) {
  365. sheet.getSheet().updateFormulasAfterCellShift(shifter, /* not used */ -1 );
  366. }
  367. workbook.updateNamesAfterCellShift(shifter);
  368. }
  369. private void validateSheetIndex(int index) {
  370. int lastSheetIx = _sheets.size() - 1;
  371. if (index < 0 || index > lastSheetIx) {
  372. throw new IllegalArgumentException("Sheet index ("
  373. + index +") is out of range (0.." + lastSheetIx + ")");
  374. }
  375. }
  376. /**
  377. * Selects a single sheet. This may be different to
  378. * the 'active' sheet (which is the sheet with focus).
  379. */
  380. public void setSelectedTab(int index) {
  381. validateSheetIndex(index);
  382. int nSheets = _sheets.size();
  383. for (int i=0; i<nSheets; i++) {
  384. getSheetAt(i).setSelected(i == index);
  385. }
  386. workbook.getWindowOne().setNumSelectedTabs((short)1);
  387. }
  388. /**
  389. * deprecated May 2008
  390. * @deprecated use setSelectedTab(int)
  391. */
  392. public void setSelectedTab(short index) {
  393. setSelectedTab((int)index);
  394. }
  395. public void setSelectedTabs(int[] indexes) {
  396. for (int i = 0; i < indexes.length; i++) {
  397. validateSheetIndex(indexes[i]);
  398. }
  399. int nSheets = _sheets.size();
  400. for (int i=0; i<nSheets; i++) {
  401. boolean bSelect = false;
  402. for (int j = 0; j < indexes.length; j++) {
  403. if (indexes[j] == i) {
  404. bSelect = true;
  405. break;
  406. }
  407. }
  408. getSheetAt(i).setSelected(bSelect);
  409. }
  410. workbook.getWindowOne().setNumSelectedTabs((short)indexes.length);
  411. }
  412. /**
  413. * Convenience method to set the active sheet. The active sheet is is the sheet
  414. * which is currently displayed when the workbook is viewed in Excel.
  415. * 'Selected' sheet(s) is a distinct concept.
  416. */
  417. public void setActiveSheet(int index) {
  418. validateSheetIndex(index);
  419. int nSheets = _sheets.size();
  420. for (int i=0; i<nSheets; i++) {
  421. getSheetAt(i).setActive(i == index);
  422. }
  423. workbook.getWindowOne().setActiveSheetIndex(index);
  424. }
  425. /**
  426. * gets the tab whose data is actually seen when the sheet is opened.
  427. * This may be different from the "selected sheet" since excel seems to
  428. * allow you to show the data of one sheet when another is seen "selected"
  429. * in the tabs (at the bottom).
  430. * @see org.apache.poi.hssf.usermodel.HSSFSheet#setSelected(boolean)
  431. */
  432. public int getActiveSheetIndex() {
  433. return workbook.getWindowOne().getActiveSheetIndex();
  434. }
  435. /**
  436. * deprecated May 2008
  437. * @deprecated - Misleading name - use getActiveSheetIndex()
  438. */
  439. public short getSelectedTab() {
  440. return (short) getActiveSheetIndex();
  441. }
  442. /**
  443. * sets the first tab that is displayed in the list of tabs
  444. * in excel.
  445. * @param index
  446. */
  447. public void setFirstVisibleTab(int index) {
  448. workbook.getWindowOne().setFirstVisibleTab(index);
  449. }
  450. /**
  451. * deprecated May 2008
  452. * @deprecated - Misleading name - use setFirstVisibleTab()
  453. */
  454. public void setDisplayedTab(short index) {
  455. setFirstVisibleTab(index);
  456. }
  457. /**
  458. * sets the first tab that is displayed in the list of tabs in excel.
  459. */
  460. public int getFirstVisibleTab() {
  461. return workbook.getWindowOne().getFirstVisibleTab();
  462. }
  463. /**
  464. * deprecated May 2008
  465. * @deprecated - Misleading name - use getFirstVisibleTab()
  466. */
  467. public short getDisplayedTab() {
  468. return (short) getFirstVisibleTab();
  469. }
  470. /**
  471. * Set the sheet name.
  472. *
  473. * @param sheetIx number (0 based)
  474. * @throws IllegalArgumentException if the name is null or invalid
  475. * or workbook already contains a sheet with this name
  476. * @see #createSheet(String)
  477. * @see org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)
  478. */
  479. public void setSheetName(int sheetIx, String name) {
  480. if (name == null) {
  481. throw new IllegalArgumentException("sheetName must not be null");
  482. }
  483. if (workbook.doesContainsSheetName(name, sheetIx)) {
  484. throw new IllegalArgumentException("The workbook already contains a sheet with this name");
  485. }
  486. validateSheetIndex(sheetIx);
  487. workbook.setSheetName(sheetIx, name);
  488. }
  489. /**
  490. * @return Sheet name for the specified index
  491. */
  492. public String getSheetName(int sheetIndex) {
  493. validateSheetIndex(sheetIndex);
  494. return workbook.getSheetName(sheetIndex);
  495. }
  496. public boolean isHidden() {
  497. return workbook.getWindowOne().getHidden();
  498. }
  499. public void setHidden(boolean hiddenFlag) {
  500. workbook.getWindowOne().setHidden(hiddenFlag);
  501. }
  502. public boolean isSheetHidden(int sheetIx) {
  503. validateSheetIndex(sheetIx);
  504. return workbook.isSheetHidden(sheetIx);
  505. }
  506. public boolean isSheetVeryHidden(int sheetIx) {
  507. validateSheetIndex(sheetIx);
  508. return workbook.isSheetVeryHidden(sheetIx);
  509. }
  510. public void setSheetHidden(int sheetIx, boolean hidden) {
  511. validateSheetIndex(sheetIx);
  512. workbook.setSheetHidden(sheetIx, hidden);
  513. }
  514. public void setSheetHidden(int sheetIx, int hidden) {
  515. validateSheetIndex(sheetIx);
  516. WorkbookUtil.validateSheetState(hidden);
  517. workbook.setSheetHidden(sheetIx, hidden);
  518. }
  519. /** Returns the index of the sheet by his name
  520. * @param name the sheet name
  521. * @return index of the sheet (0 based)
  522. */
  523. public int getSheetIndex(String name){
  524. return workbook.getSheetIndex(name);
  525. }
  526. /** Returns the index of the given sheet
  527. * @param sheet the sheet to look up
  528. * @return index of the sheet (0 based). <tt>-1</tt> if not found
  529. */
  530. public int getSheetIndex(org.apache.poi.ss.usermodel.Sheet sheet) {
  531. for(int i=0; i<_sheets.size(); i++) {
  532. if(_sheets.get(i) == sheet) {
  533. return i;
  534. }
  535. }
  536. return -1;
  537. }
  538. /**
  539. * Returns the external sheet index of the sheet
  540. * with the given internal index, creating one
  541. * if needed.
  542. * Used by some of the more obscure formula and
  543. * named range things.
  544. * @deprecated for POI internal use only (formula parsing). This method is likely to
  545. * be removed in future versions of POI.
  546. */
  547. public int getExternalSheetIndex(int internalSheetIndex) {
  548. return workbook.checkExternSheet(internalSheetIndex);
  549. }
  550. /**
  551. * @deprecated for POI internal use only (formula rendering). This method is likely to
  552. * be removed in future versions of POI.
  553. */
  554. public String findSheetNameFromExternSheet(int externSheetIndex){
  555. // TODO - don't expose internal ugliness like externSheet indexes to the user model API
  556. return workbook.findSheetNameFromExternSheet(externSheetIndex);
  557. }
  558. /**
  559. * @deprecated for POI internal use only (formula rendering). This method is likely to
  560. * be removed in future versions of POI.
  561. *
  562. * @param refIndex Index to REF entry in EXTERNSHEET record in the Link Table
  563. * @param definedNameIndex zero-based to DEFINEDNAME or EXTERNALNAME record
  564. * @return the string representation of the defined or external name
  565. */
  566. public String resolveNameXText(int refIndex, int definedNameIndex) {
  567. // TODO - make this less cryptic / move elsewhere
  568. return workbook.resolveNameXText(refIndex, definedNameIndex);
  569. }
  570. /**
  571. * create an HSSFSheet for this HSSFWorkbook, adds it to the sheets and returns
  572. * the high level representation. Use this to create new sheets.
  573. *
  574. * @return HSSFSheet representing the new sheet.
  575. */
  576. public HSSFSheet createSheet()
  577. {
  578. HSSFSheet sheet = new HSSFSheet(this);
  579. _sheets.add(sheet);
  580. workbook.setSheetName(_sheets.size() - 1, "Sheet" + (_sheets.size() - 1));
  581. boolean isOnlySheet = _sheets.size() == 1;
  582. sheet.setSelected(isOnlySheet);
  583. sheet.setActive(isOnlySheet);
  584. return sheet;
  585. }
  586. /**
  587. * create an HSSFSheet from an existing sheet in the HSSFWorkbook.
  588. *
  589. * @return HSSFSheet representing the cloned sheet.
  590. */
  591. public HSSFSheet cloneSheet(int sheetIndex) {
  592. validateSheetIndex(sheetIndex);
  593. HSSFSheet srcSheet = _sheets.get(sheetIndex);
  594. String srcName = workbook.getSheetName(sheetIndex);
  595. HSSFSheet clonedSheet = srcSheet.cloneSheet(this);
  596. clonedSheet.setSelected(false);
  597. clonedSheet.setActive(false);
  598. String name = getUniqueSheetName(srcName);
  599. int newSheetIndex = _sheets.size();
  600. _sheets.add(clonedSheet);
  601. workbook.setSheetName(newSheetIndex, name);
  602. // Check this sheet has an autofilter, (which has a built-in NameRecord at workbook level)
  603. int filterDbNameIndex = findExistingBuiltinNameRecordIdx(sheetIndex, NameRecord.BUILTIN_FILTER_DB);
  604. if (filterDbNameIndex != -1) {
  605. NameRecord newNameRecord = workbook.cloneFilter(filterDbNameIndex, newSheetIndex);
  606. HSSFName newName = new HSSFName(this, newNameRecord);
  607. names.add(newName);
  608. }
  609. // TODO - maybe same logic required for other/all built-in name records
  610. workbook.cloneDrawings(clonedSheet.getSheet());
  611. return clonedSheet;
  612. }
  613. private String getUniqueSheetName(String srcName) {
  614. int uniqueIndex = 2;
  615. String baseName = srcName;
  616. int bracketPos = srcName.lastIndexOf('(');
  617. if (bracketPos > 0 && srcName.endsWith(")")) {
  618. String suffix = srcName.substring(bracketPos + 1, srcName.length() - ")".length());
  619. try {
  620. uniqueIndex = Integer.parseInt(suffix.trim());
  621. uniqueIndex++;
  622. baseName=srcName.substring(0, bracketPos).trim();
  623. } catch (NumberFormatException e) {
  624. // contents of brackets not numeric
  625. }
  626. }
  627. while (true) {
  628. // Try and find the next sheet name that is unique
  629. String index = Integer.toString(uniqueIndex++);
  630. String name;
  631. if (baseName.length() + index.length() + 2 < 31) {
  632. name = baseName + " (" + index + ")";
  633. } else {
  634. name = baseName.substring(0, 31 - index.length() - 2) + "(" + index + ")";
  635. }
  636. //If the sheet name is unique, then set it otherwise move on to the next number.
  637. if (workbook.getSheetIndex(name) == -1) {
  638. return name;
  639. }
  640. }
  641. }
  642. /**
  643. * Create a new sheet for this Workbook and return the high level representation.
  644. * Use this to create new sheets.
  645. *
  646. * <p>
  647. * Note that Excel allows sheet names up to 31 chars in length but other applications
  648. * (such as OpenOffice) allow more. Some versions of Excel crash with names longer than 31 chars,
  649. * others - truncate such names to 31 character.
  650. * </p>
  651. * <p>
  652. * POI's SpreadsheetAPI silently truncates the input argument to 31 characters.
  653. * Example:
  654. *
  655. * <pre><code>
  656. * Sheet sheet = workbook.createSheet("My very long sheet name which is longer than 31 chars"); // will be truncated
  657. * assert 31 == sheet.getSheetName().length();
  658. * assert "My very long sheet name which i" == sheet.getSheetName();
  659. * </code></pre>
  660. * </p>
  661. *
  662. * Except the 31-character constraint, Excel applies some other rules:
  663. * <p>
  664. * Sheet name MUST be unique in the workbook and MUST NOT contain the any of the following characters:
  665. * <ul>
  666. * <li> 0x0000 </li>
  667. * <li> 0x0003 </li>
  668. * <li> colon (:) </li>
  669. * <li> backslash (\) </li>
  670. * <li> asterisk (*) </li>
  671. * <li> question mark (?) </li>
  672. * <li> forward slash (/) </li>
  673. * <li> opening square bracket ([) </li>
  674. * <li> closing square bracket (]) </li>
  675. * </ul>
  676. * The string MUST NOT begin or end with the single quote (') character.
  677. * </p>
  678. *
  679. * @param sheetname sheetname to set for the sheet.
  680. * @return Sheet representing the new sheet.
  681. * @throws IllegalArgumentException if the name is null or invalid
  682. * or workbook already contains a sheet with this name
  683. * @see org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)
  684. */
  685. public HSSFSheet createSheet(String sheetname)
  686. {
  687. if (sheetname == null) {
  688. throw new IllegalArgumentException("sheetName must not be null");
  689. }
  690. if (workbook.doesContainsSheetName( sheetname, _sheets.size() ))
  691. throw new IllegalArgumentException( "The workbook already contains a sheet of this name" );
  692. HSSFSheet sheet = new HSSFSheet(this);
  693. workbook.setSheetName(_sheets.size(), sheetname);
  694. _sheets.add(sheet);
  695. boolean isOnlySheet = _sheets.size() == 1;
  696. sheet.setSelected(isOnlySheet);
  697. sheet.setActive(isOnlySheet);
  698. return sheet;
  699. }
  700. /**
  701. * get the number of spreadsheets in the workbook (this will be three after serialization)
  702. * @return number of sheets
  703. */
  704. public int getNumberOfSheets()
  705. {
  706. return _sheets.size();
  707. }
  708. public int getSheetIndexFromExternSheetIndex(int externSheetNumber) {
  709. return workbook.getSheetIndexFromExternSheetIndex(externSheetNumber);
  710. }
  711. private HSSFSheet[] getSheets() {
  712. HSSFSheet[] result = new HSSFSheet[_sheets.size()];
  713. _sheets.toArray(result);
  714. return result;
  715. }
  716. /**
  717. * Get the HSSFSheet object at the given index.
  718. * @param index of the sheet number (0-based physical & logical)
  719. * @return HSSFSheet at the provided index
  720. */
  721. public HSSFSheet getSheetAt(int index)
  722. {
  723. validateSheetIndex(index);
  724. return (HSSFSheet) _sheets.get(index);
  725. }
  726. /**
  727. * Get sheet with the given name (case insensitive match)
  728. * @param name of the sheet
  729. * @return HSSFSheet with the name provided or <code>null</code> if it does not exist
  730. */
  731. public HSSFSheet getSheet(String name)
  732. {
  733. HSSFSheet retval = null;
  734. for (int k = 0; k < _sheets.size(); k++)
  735. {
  736. String sheetname = workbook.getSheetName(k);
  737. if (sheetname.equalsIgnoreCase(name))
  738. {
  739. retval = (HSSFSheet) _sheets.get(k);
  740. }
  741. }
  742. return retval;
  743. }
  744. /**
  745. * Removes sheet at the given index.<p/>
  746. *
  747. * Care must be taken if the removed sheet is the currently active or only selected sheet in
  748. * the workbook. There are a few situations when Excel must have a selection and/or active
  749. * sheet. (For example when printing - see Bug 40414).<br/>
  750. *
  751. * This method makes sure that if the removed sheet was active, another sheet will become
  752. * active in its place. Furthermore, if the removed sheet was the only selected sheet, another
  753. * sheet will become selected. The newly active/selected sheet will have the same index, or
  754. * one less if the removed sheet was the last in the workbook.
  755. *
  756. * @param index of the sheet (0-based)
  757. */
  758. public void removeSheetAt(int index) {
  759. validateSheetIndex(index);
  760. boolean wasActive = getSheetAt(index).isActive();
  761. boolean wasSelected = getSheetAt(index).isSelected();
  762. _sheets.remove(index);
  763. workbook.removeSheet(index);
  764. // set the remaining active/selected sheet
  765. int nSheets = _sheets.size();
  766. if (nSheets < 1) {
  767. // nothing more to do if there are no sheets left
  768. return;
  769. }
  770. // the index of the closest remaining sheet to the one just deleted
  771. int newSheetIndex = index;
  772. if (newSheetIndex >= nSheets) {
  773. newSheetIndex = nSheets-1;
  774. }
  775. if (wasActive) {
  776. setActiveSheet(newSheetIndex);
  777. }
  778. if (wasSelected) {
  779. boolean someOtherSheetIsStillSelected = false;
  780. for (int i =0; i < nSheets; i++) {
  781. if (getSheetAt(i).isSelected()) {
  782. someOtherSheetIsStillSelected = true;
  783. break;
  784. }
  785. }
  786. if (!someOtherSheetIsStillSelected) {
  787. setSelectedTab(newSheetIndex);
  788. }
  789. }
  790. }
  791. /**
  792. * determine whether the Excel GUI will backup the workbook when saving.
  793. *
  794. * @param backupValue true to indicate a backup will be performed.
  795. */
  796. public void setBackupFlag(boolean backupValue)
  797. {
  798. BackupRecord backupRecord = workbook.getBackupRecord();
  799. backupRecord.setBackup(backupValue ? (short) 1
  800. : (short) 0);
  801. }
  802. /**
  803. * determine whether the Excel GUI will backup the workbook when saving.
  804. *
  805. * @return the current setting for backups.
  806. */
  807. public boolean getBackupFlag()
  808. {
  809. BackupRecord backupRecord = workbook.getBackupRecord();
  810. return (backupRecord.getBackup() == 0) ? false
  811. : true;
  812. }
  813. /**
  814. * Sets the repeating rows and columns for a sheet (as found in
  815. * 2003:File->PageSetup->Sheet, 2007:Page Layout->Print Titles).
  816. * This is function is included in the workbook
  817. * because it creates/modifies name records which are stored at the
  818. * workbook level.
  819. * <p>
  820. * To set just repeating columns:
  821. * <pre>
  822. * workbook.setRepeatingRowsAndColumns(0,0,1,-1-1);
  823. * </pre>
  824. * To set just repeating rows:
  825. * <pre>
  826. * workbook.setRepeatingRowsAndColumns(0,-1,-1,0,4);
  827. * </pre>
  828. * To remove all repeating rows and columns for a sheet.
  829. * <pre>
  830. * workbook.setRepeatingRowsAndColumns(0,-1,-1,-1,-1);
  831. * </pre>
  832. *
  833. * @param sheetIndex 0 based index to sheet.
  834. * @param startColumn 0 based start of repeating columns.
  835. * @param endColumn 0 based end of repeating columns.
  836. * @param startRow 0 based start of repeating rows.
  837. * @param endRow 0 based end of repeating rows.
  838. */
  839. public void setRepeatingRowsAndColumns(int sheetIndex,
  840. int startColumn, int endColumn,
  841. int startRow, int endRow)
  842. {
  843. // Check arguments
  844. if (startColumn == -1 && endColumn != -1) throw new IllegalArgumentException("Invalid column range specification");
  845. if (startRow == -1 && endRow != -1) throw new IllegalArgumentException("Invalid row range specification");
  846. if (startColumn < -1 || startColumn >= MAX_COLUMN) throw new IllegalArgumentException("Invalid column range specification");
  847. if (endColumn < -1 || endColumn >= MAX_COLUMN) throw new IllegalArgumentException("Invalid column range specification");
  848. if (startRow < -1 || startRow > MAX_ROW) throw new IllegalArgumentException("Invalid row range specification");
  849. if (endRow < -1 || endRow > MAX_ROW) throw new IllegalArgumentException("Invalid row range specification");
  850. if (startColumn > endColumn) throw new IllegalArgumentException("Invalid column range specification");
  851. if (startRow > endRow) throw new IllegalArgumentException("Invalid row range specification");
  852. HSSFSheet sheet = getSheetAt(sheetIndex);
  853. short externSheetIndex = getWorkbook().checkExternSheet(sheetIndex);
  854. boolean settingRowAndColumn =
  855. startColumn != -1 && endColumn != -1 && startRow != -1 && endRow != -1;
  856. boolean removingRange =
  857. startColumn == -1 && endColumn == -1 && startRow == -1 && endRow == -1;
  858. int rowColHeaderNameIndex = findExistingBuiltinNameRecordIdx(sheetIndex, NameRecord.BUILTIN_PRINT_TITLE);
  859. if (removingRange) {
  860. if (rowColHeaderNameIndex >= 0) {
  861. workbook.removeName(rowColHeaderNameIndex);
  862. }
  863. return;
  864. }
  865. boolean isNewRecord;
  866. NameRecord nameRecord;
  867. if (rowColHeaderNameIndex < 0) {
  868. //does a lot of the house keeping for builtin records, like setting lengths to zero etc
  869. nameRecord = workbook.createBuiltInName(NameRecord.BUILTIN_PRINT_TITLE, sheetIndex+1);
  870. isNewRecord = true;
  871. } else {
  872. nameRecord = workbook.getNameRecord(rowColHeaderNameIndex);
  873. isNewRecord = false;
  874. }
  875. List temp = new ArrayList();
  876. if (settingRowAndColumn) {
  877. final int exprsSize = 2 * 11 + 1; // 2 * Area3DPtg.SIZE + UnionPtg.SIZE
  878. temp.add(new MemFuncPtg(exprsSize));
  879. }
  880. if (startColumn >= 0) {
  881. Area3DPtg colArea = new Area3DPtg(0, MAX_ROW, startColumn, endColumn,
  882. false, false, false, false, externSheetIndex);
  883. temp.add(colArea);
  884. }
  885. if (startRow >= 0) {
  886. Area3DPtg rowArea = new Area3DPtg(startRow, endRow, 0, MAX_COLUMN,
  887. false, false, false, false, externSheetIndex);
  888. temp.add(rowArea);
  889. }
  890. if (settingRowAndColumn) {
  891. temp.add(UnionPtg.instance);
  892. }
  893. Ptg[] ptgs = new Ptg[temp.size()];
  894. temp.toArray(ptgs);
  895. nameRecord.setNameDefinition(ptgs);
  896. if (isNewRecord)
  897. {
  898. HSSFName newName = new HSSFName(this, nameRecord, nameRecord.isBuiltInName() ? null : workbook.getNameCommentRecord(nameRecord));
  899. names.add(newName);
  900. }
  901. HSSFPrintSetup printSetup = sheet.getPrintSetup();
  902. printSetup.setValidSettings(false);
  903. sheet.setActive(true);
  904. }
  905. int findExistingBuiltinNameRecordIdx(int sheetIndex, byte builtinCode) {
  906. for(int defNameIndex =0; defNameIndex<names.size(); defNameIndex++) {
  907. NameRecord r = workbook.getNameRecord(defNameIndex);
  908. if (r == null) {
  909. throw new RuntimeException("Unable to find all defined names to iterate over");
  910. }
  911. if (!r.isBuiltInName() || r.getBuiltInName() != builtinCode) {
  912. continue;
  913. }
  914. if (r.getSheetNumber() -1 == sheetIndex) {
  915. return defNameIndex;
  916. }
  917. }
  918. return -1;
  919. }
  920. /**
  921. * create a new Font and add it to the workbook's font table
  922. * @return new font object
  923. */
  924. public HSSFFont createFont()
  925. {
  926. FontRecord font = workbook.createNewFont();
  927. short fontindex = (short) (getNumberOfFonts() - 1);
  928. if (fontindex > 3)
  929. {
  930. fontindex++; // THERE IS NO FOUR!!
  931. }
  932. if(fontindex == Short.MAX_VALUE){
  933. throw new IllegalArgumentException("Maximum number of fonts was exceeded");
  934. }
  935. // Ask getFontAt() to build it for us,
  936. // so it gets properly cached
  937. return getFontAt(fontindex);
  938. }
  939. /**
  940. * Finds a font that matches the one with the supplied attributes
  941. */
  942. public HSSFFont findFont(short boldWeight, short color, short fontHeight,
  943. String name, boolean italic, boolean strikeout,
  944. short typeOffset, byte underline)
  945. {
  946. for (short i=0; i<=getNumberOfFonts(); i++) {
  947. // Remember - there is no 4!
  948. if(i == 4) continue;
  949. HSSFFont hssfFont = getFontAt(i);
  950. if (hssfFont.getBoldweight() == boldWeight
  951. && hssfFont.getColor() == color
  952. && hssfFont.getFontHeight() == fontHeight
  953. && hssfFont.getFontName().equals(name)
  954. && hssfFont.getItalic() == italic
  955. && hssfFont.getStrikeout() == strikeout
  956. && hssfFont.getTypeOffset() == typeOffset
  957. && hssfFont.getUnderline() == underline)
  958. {
  959. return hssfFont;
  960. }
  961. }
  962. return null;
  963. }
  964. /**
  965. * get the number of fonts in the font table
  966. * @return number of fonts
  967. */
  968. public short getNumberOfFonts()
  969. {
  970. return (short) workbook.getNumberOfFontRecords();
  971. }
  972. /**
  973. * Get the font at the given index number
  974. * @param idx index number
  975. * @return HSSFFont at the index
  976. */
  977. public HSSFFont getFontAt(short idx) {
  978. if(fonts == null) fonts = new Hashtable();
  979. // So we don't confuse users, give them back
  980. // the same object every time, but create
  981. // them lazily
  982. Short sIdx = Short.valueOf(idx);
  983. if(fonts.containsKey(sIdx)) {
  984. return (HSSFFont)fonts.get(sIdx);
  985. }
  986. FontRecord font = workbook.getFontRecordAt(idx);
  987. HSSFFont retval = new HSSFFont(idx, font);
  988. fonts.put(sIdx, retval);
  989. return retval;
  990. }
  991. /**
  992. * Reset the fonts cache, causing all new calls
  993. * to getFontAt() to create new objects.
  994. * Should only be called after deleting fonts,
  995. * and that's not something you should normally do
  996. */
  997. protected void resetFontCache() {
  998. fonts = new Hashtable();
  999. }
  1000. /**
  1001. * Create a new Cell style and add it to the workbook's style table.
  1002. * You can define up to 4000 unique styles in a .xls workbook.
  1003. *
  1004. * @return the new Cell Style object
  1005. * @throws IllegalStateException if the maximum number of cell styles exceeded the limit
  1006. */
  1007. public HSSFCellStyle createCellStyle()
  1008. {
  1009. if(workbook.getNumExFormats() == MAX_STYLES) {
  1010. throw new IllegalStateException("The maximum number of cell styles was exceeded. " +
  1011. "You can define up to 4000 styles in a .xls workbook");
  1012. }
  1013. ExtendedFormatRecord xfr = workbook.createCellXF();
  1014. short index = (short) (getNumCellStyles() - 1);
  1015. HSSFCellStyle style = new HSSFCellStyle(index, xfr, this);
  1016. return style;
  1017. }
  1018. /**
  1019. * get the number of styles the workbook contains
  1020. * @return count of cell styles
  1021. */
  1022. public short getNumCellStyles()
  1023. {
  1024. return (short) workbook.getNumExFormats();
  1025. }
  1026. /**
  1027. * get the cell style object at the given index
  1028. * @param idx index within the set of styles
  1029. * @return HSSFCellStyle object at the index
  1030. */
  1031. public HSSFCellStyle getCellStyleAt(short idx)
  1032. {
  1033. ExtendedFormatRecord xfr = workbook.getExFormatAt(idx);
  1034. HSSFCellStyle style = new HSSFCellStyle(idx, xfr, this);
  1035. return style;
  1036. }
  1037. /**
  1038. * Method write - write out this workbook to an Outputstream. Constructs
  1039. * a new POI POIFSFileSystem, passes in the workbook binary representation and
  1040. * writes it out.
  1041. *
  1042. * @param stream - the java OutputStream you wish to write the XLS to
  1043. *
  1044. * @exception IOException if anything can't be written.
  1045. * @see org.apache.poi.poifs.filesystem.POIFSFileSystem
  1046. */
  1047. public void write(OutputStream stream)
  1048. throws IOException
  1049. {
  1050. byte[] bytes = getBytes();
  1051. POIFSFileSystem fs = new POIFSFileSystem();
  1052. // For tracking what we've written out, used if we're
  1053. // going to be preserving nodes
  1054. List<String> excepts = new ArrayList<String>(1);
  1055. // Write out the Workbook stream
  1056. fs.createDocument(new ByteArrayInputStream(bytes), "Workbook");
  1057. // Write out our HPFS properties, if we have them
  1058. writeProperties(fs, excepts);
  1059. if (preserveNodes) {
  1060. // Don't write out the old Workbook, we'll be doing our new one
  1061. excepts.add("Workbook");
  1062. // If the file had WORKBOOK instead of Workbook, we'll write it
  1063. // out correctly shortly, so don't include the old one
  1064. excepts.add("WORKBOOK");
  1065. // Copy over all the other nodes to our new poifs
  1066. copyNodes(this.directory, fs.getRoot(), excepts);
  1067. // YK: preserve StorageClsid, it is important for embedded workbooks,
  1068. // see Bugzilla 47920
  1069. fs.getRoot().setStorageClsid(this.directory.getStorageClsid());
  1070. }
  1071. fs.writeFilesystem(stream);
  1072. }
  1073. /**
  1074. * Totals the sizes of all sheet records and eventually serializes them
  1075. */
  1076. private static final class SheetRecordCollector implements RecordVisitor {
  1077. private List _list;
  1078. private int _totalSize;
  1079. public SheetRecordCollector() {
  1080. _totalSize = 0;
  1081. _list = new ArrayList(128);
  1082. }
  1083. public int getTotalSize() {
  1084. return _totalSize;
  1085. }
  1086. public void visitRecord(Record r) {
  1087. _list.add(r);
  1088. _totalSize+=r.getRecordSize();
  1089. }
  1090. public int serialize(int offset, byte[] data) {
  1091. int result = 0;
  1092. int nRecs = _list.size();
  1093. for(int i=0; i<nRecs; i++) {
  1094. Record rec = (Record)_list.get(i);
  1095. result += rec.serialize(offset + result, data);
  1096. }
  1097. return result;
  1098. }
  1099. }
  1100. /**
  1101. * Method getBytes - get the bytes of just the HSSF portions of the XLS file.
  1102. * Use this to construct a POI POIFSFileSystem yourself.
  1103. *
  1104. *
  1105. * @return byte[] array containing the binary representation of this workbook and all contained
  1106. * sheets, rows, cells, etc.
  1107. */
  1108. public byte[] getBytes() {
  1109. if (log.check( POILogger.DEBUG )) {
  1110. log.log(DEBUG, "HSSFWorkbook.getBytes()");
  1111. }
  1112. HSSFSheet[] sheets = getSheets();
  1113. int nSheets = sheets.length;
  1114. // before getting the workbook size we must tell the sheets that
  1115. // serialization is about to occur.
  1116. for (int i = 0; i < nSheets; i++) {
  1117. sheets[i].getSheet().preSerialize();
  1118. }
  1119. int totalsize = workbook.getSize();
  1120. // pre-calculate all the sheet sizes and set BOF indexes
  1121. SheetRecordCollector[] srCollectors = new SheetRecordCollector[nSheets];
  1122. for (int k = 0; k < nSheets; k++) {
  1123. workbook.setSheetBof(k, totalsize);
  1124. SheetRecordCollector src = new SheetRecordCollector();
  1125. sheets[k].getSheet().visitContainedRecords(src, totalsize);
  1126. totalsize += src.getTotalSize();
  1127. srCollectors[k] = src;
  1128. }
  1129. byte[] retval = new byte[totalsize];
  1130. int pos = workbook.serialize(0, retval);
  1131. for (int k = 0; k < nSheets; k++) {
  1132. SheetRecordCollector src = srCollectors[k];
  1133. int serializedSize = src.serialize(pos, retval);
  1134. if (serializedSize != src.getTotalSize()) {
  1135. // Wrong offset values have been passed in the call to setSheetBof() above.
  1136. // For books with more than one sheet, this discrepancy would cause excel
  1137. // to report errors and loose data while reading the workbook
  1138. throw new IllegalStateException("Actual serialized sheet size (" + serializedSize
  1139. + ") differs from pre-calculated size (" + src.getTotalSize()
  1140. + ") for sheet (" + k + ")");
  1141. // TODO - add similar sanity check to ensure that Sheet.serializeIndexRecord() does not write mis-aligned offsets either
  1142. }
  1143. pos += serializedSize;
  1144. }
  1145. return retval;
  1146. }
  1147. /** @deprecated Do not call this method from your applications. Use the methods
  1148. * available in the HSSFRow to add string HSSFCells
  1149. */
  1150. public int addSSTString(String string)
  1151. {
  1152. return workbook.addSSTString(new UnicodeString(string));
  1153. }
  1154. /** @deprecated Do not call this method from your applications. Use the methods
  1155. * available in the HSSFRow to get string HSSFCells
  1156. */
  1157. public String getSSTString(int index)
  1158. {
  1159. return workbook.getSSTString(index).getString();
  1160. }
  1161. InternalWorkbook getWorkbook() {
  1162. return workbook;
  1163. }
  1164. public int getNumberOfNames(){
  1165. int result = names.size();
  1166. return result;
  1167. }
  1168. public HSSFName getName(String name) {
  1169. int nameIndex = getNameIndex(name);
  1170. if (nameIndex < 0) {
  1171. return null;
  1172. }
  1173. return (HSSFName) names.get(nameIndex);
  1174. }
  1175. public HSSFName getNameAt(int nameIndex) {
  1176. int nNames = names.size();
  1177. if (nNames < 1) {
  1178. throw new IllegalStateException("There are no defined names in this workbook");
  1179. }
  1180. if (nameIndex < 0 || nameIndex > nNames) {
  1181. throw new IllegalArgumentException("Specified name index " + nameIndex
  1182. + " is outside the allowable range (0.." + (nNames-1) + ").");
  1183. }
  1184. return (HSSFName) names.get(nameIndex);
  1185. }
  1186. public NameRecord getNameRecord(int nameIndex) {
  1187. return getWorkbook().getNameRecord(nameIndex);
  1188. }
  1189. /** gets the named range name
  1190. * @param index the named range index (0 based)
  1191. * @return named range name
  1192. */
  1193. public String getNameName(int index){
  1194. String result = getNameAt(index).getNameName();
  1195. return result;
  1196. }
  1197. /**
  1198. * Sets the printarea for the sheet provided
  1199. * <p>
  1200. * i.e. Reference = $A$1:$B$2
  1201. * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java)
  1202. * @param reference Valid name Reference for the Print Area
  1203. */
  1204. public void setPrintArea(int sheetIndex, String reference)
  1205. {
  1206. NameRecord name = workbook.getSpecificBuiltinRecord(NameRecord.BUILTIN_PRINT_AREA, sheetIndex+1);
  1207. if (name == null) {
  1208. name = workbook.createBuiltInName(NameRecord.BUILTIN_PRINT_AREA, sheetIndex+1);
  1209. // adding one here because 0 indicates a global named region; doesn't make sense for print areas
  1210. }
  1211. String[] parts = COMMA_PATTERN.split(reference);
  1212. StringBuffer sb = new StringBuffer(32);
  1213. for (int i = 0; i < parts.length; i++) {
  1214. if(i>0) {
  1215. sb.append(",");
  1216. }
  1217. SheetNameFormatter.appendFormat(sb, getSheetName(sheetIndex));
  1218. sb.append("!");
  1219. sb.append(parts[i]);
  1220. }
  1221. name.setNameDefinition(HSSFFormulaParser.parse(sb.toString(), this, FormulaType.NAMEDRANGE, sheetIndex));
  1222. }
  1223. /**
  1224. * For the Convenience of Java Programmers maintaining pointers.
  1225. * @see #setPrintArea(int, String)
  1226. * @param sheetIndex Zero-based sheet index (0 = First Sheet)
  1227. * @param startColumn Column to begin printarea
  1228. * @param endColumn Column to end the printarea
  1229. * @param startRow Row to begin the printarea
  1230. * @param endRow Row to end the printarea
  1231. */
  1232. public void setPrintArea(int sheetIndex, int startColumn, int endColumn,
  1233. int startRow, int endRow) {
  1234. //using absolute references because they don't get copied and pasted anyway
  1235. CellReference cell = new CellReference(startRow, startColumn, true, true);
  1236. String reference = cell.formatAsString();
  1237. cell = new CellReference(endRow, endColumn, true, true);
  1238. reference = reference+":"+cell.formatAsString();
  1239. setPrintArea(sheetIndex, reference);
  1240. }
  1241. /**
  1242. * Retrieves the reference for the printarea of the specified sheet, the sheet name is appended to the reference even if it was not specified.
  1243. * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java)
  1244. * @return String Null if no print area has been defined
  1245. */
  1246. public String getPrintArea(int sheetIndex) {
  1247. NameRecord name = workbook.getSpecificBuiltinRecord(NameRecord.BUILTIN_PRINT_AREA, sheetIndex+1);
  1248. //adding one here because 0 indicates a global named region; doesn't make sense for print areas
  1249. if (name == null) {
  1250. return null;
  1251. }
  1252. return HSSFFormulaParser.toFormulaString(this, name.getNameDefinition());
  1253. }
  1254. /**
  1255. * Delete the printarea for the sheet specified
  1256. * @param sheetIndex Zero-based sheet index (0 = First Sheet)
  1257. */
  1258. public void removePrintArea(int sheetIndex) {
  1259. getWorkbook().removeBuiltinRecord(NameRecord.BUILTIN_PRINT_AREA, sheetIndex+1);
  1260. }
  1261. /** creates a new named range and add it to the model
  1262. * @return named range high level
  1263. */
  1264. public HSSFName createName(){
  1265. NameRecord nameRecord = workbook.createName();
  1266. HSSFName newName = new HSSFName(this, nameRecord);
  1267. names.add(newName);
  1268. return newName;
  1269. }
  1270. public int getNameIndex(String name) {
  1271. for (int k = 0; k < names.size(); k++) {
  1272. String nameName = getNameName(k);
  1273. if (nameName.equalsIgnoreCase(name)) {
  1274. return k;
  1275. }
  1276. }
  1277. return -1;
  1278. }
  1279. public void removeName(int index){
  1280. names.remove(index);
  1281. workbook.removeName(index);
  1282. }
  1283. /**
  1284. * Returns the instance of HSSFDataFormat for this workbook.
  1285. * @return the HSSFDataFormat object
  1286. * @see org.apache.poi.hssf.record.FormatRecord
  1287. * @see org.apache.poi.hssf.record.Record
  1288. */
  1289. public HSSFDataFormat createDataFormat() {
  1290. if (formatter == null)
  1291. formatter = new HSSFDataFormat(workbook);
  1292. return formatter;
  1293. }
  1294. public void removeName(String name) {
  1295. int index = getNameIndex(name);
  1296. removeName(index);
  1297. }
  1298. public HSSFPalette getCustomPalette()
  1299. {
  1300. return new HSSFPalette(workbook.getCustomPalette());
  1301. }
  1302. /** Test only. Do not use */
  1303. public void insertChartRecord()
  1304. {
  1305. int loc = workbook.findFirstRecordLocBySid(SSTRecord.sid);
  1306. byte[] data = {
  1307. (byte)0x0F, (byte)0x00, (byte)0x00, (byte)0xF0, (byte)0x52,
  1308. (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
  1309. (byte)0x06, (byte)0xF0, (byte)0x18, (byte)0x00, (byte)0x00,
  1310. (byte)0x00, (byte)0x01, (byte)0x08, (byte)0x00, (byte)0x00,
  1311. (byte)0x02, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x02,
  1312. (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00,
  1313. (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00,
  1314. (byte)0x00, (byte)0x03, (byte)0x00, (byte)0x00, (byte)0x00,
  1315. (byte)0x33, (byte)0x00, (byte)0x0B, (byte)0xF0, (byte)0x12,
  1316. (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xBF, (byte)0x00,
  1317. (byte)0x08, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x81,
  1318. (byte)0x01, (byte)0x09, (byte)0x00, (byte)0x00, (byte)0x08,
  1319. (byte)0xC0, (byte)0x01, (byte)0x40, (byte)0x00, (byte)0x00,
  1320. (byte)0x08, (byte)0x40, (byte)0x00, (byte)0x1E, (byte)0xF1,
  1321. (byte)0x10, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0D,
  1322. (byte)0x00, (byte)0x00, (byte)0x08, (byte)0x0C, (byte)0x00,
  1323. (byte)0x00, (byte)0x08, (byte)0x17, (byte)0x00, (byte)0x00,
  1324. (byte)0x08, (byte)0xF7, (byte)0x00, (byte)0x00, (byte)0x10,
  1325. };
  1326. UnknownRecord r = new UnknownRecord((short)0x00EB, data);
  1327. workbook.getRecords().add(loc, r);
  1328. }
  1329. /**
  1330. * Spits out a list of all the drawing records in the workbook.
  1331. */
  1332. public void dumpDrawingGroupRecords(boolean fat)
  1333. {
  1334. DrawingGroupRecord r = (DrawingGroupRecord) workbook.findFirstRecordBySid( DrawingGroupRecord.sid );
  1335. r.decode();
  1336. List escherRecords = r.getEscherRecords();
  1337. PrintWriter w = new PrintWriter(System.out);
  1338. for ( Iterator iterator = escherRecords.iterator(); iterator.hasNext(); )
  1339. {
  1340. EscherRecord escherRecord = (EscherRecord) iterator.next();
  1341. if (fat)
  1342. System.out.println(escherRecord.toString());
  1343. else
  1344. escherRecord.display(w, 0);
  1345. }
  1346. w.flush();
  1347. }
  1348. void initDrawings(){
  1349. DrawingManager2 mgr = workbook.findDrawingGroup();
  1350. if(mgr != null) {
  1351. for(int i=0; i < getNumberOfSheets(); i++) {
  1352. getSheetAt(i).getDrawingPatriarch();
  1353. }
  1354. } else {
  1355. workbook.createDrawingGroup();
  1356. }
  1357. }
  1358. /**
  1359. * Adds a picture to the workbook.
  1360. *
  1361. * @param pictureData The bytes of the picture
  1362. * @param format The format of the picture. One of <code>PICTURE_TYPE_*</code>
  1363. *
  1364. * @return the index to this picture (1 based).
  1365. */
  1366. public int addPicture(byte[] pictureData, int format)
  1367. {
  1368. initDrawings();
  1369. byte[] uid = DigestUtils.md5(pictureData);
  1370. EscherBitmapBlip blipRecord = new EscherBitmapBlip();
  1371. blipRecord.setRecordId( (short) ( EscherBitmapBlip.RECORD_ID_START + format ) );
  1372. switch (format)
  1373. {
  1374. case PICTURE_TYPE_EMF:
  1375. blipRecord.setOptions(HSSFPictureData.MSOBI_EMF);
  1376. break;
  1377. case PICTURE_TYPE_WMF:
  1378. blipRecord.setOptions(HSSFPictureData.MSOBI_WMF);
  1379. break;
  1380. case PICTURE_TYPE_PICT:
  1381. blipRecord.setOptions(HSSFPictureData.MSOBI_PICT);
  1382. break;
  1383. case PICTURE_TYPE_PNG:
  1384. blipRecord.setOptions(HSSFPictureData.MSOBI_PNG);
  1385. break;
  1386. case HSSFWorkbook.PICTURE_TYPE_JPEG:
  1387. blipRecord.setOptions(HSSFPictureData.MSOBI_JPEG);
  1388. break;
  1389. case HSSFWorkbook.PICTURE_TYPE_DIB:
  1390. blipRecord.setOptions(HSSFPictureData.MSOBI_DIB);
  1391. break;
  1392. }
  1393. blipRecord.setUID( uid );
  1394. blipRecord.setMarker( (byte) 0xFF );
  1395. blipRecord.setPictureData( pictureData );
  1396. EscherBSERecord r = new EscherBSERecord();
  1397. r.setRecordId( EscherBSERecord.RECORD_ID );
  1398. r.setOptions( (short) ( 0x0002 | ( format << 4 ) ) );
  1399. r.setBlipTypeMacOS( (byte) format );
  1400. r.setBlipTypeWin32( (byte) format );
  1401. r.setUid( uid );
  1402. r.setTag( (short) 0xFF );
  1403. r.setSize( pictureData.length + 25 );
  1404. r.setRef( 1 );
  1405. r.setOffset( 0 );
  1406. r.setBlipRecord( blipRecord );
  1407. return workbook.addBSERecord( r );
  1408. }
  1409. /**
  1410. * Gets all pictures from the Workbook.
  1411. *
  1412. * @return the list of pictures (a list of {@link HSSFPictureData} objects.)
  1413. */
  1414. public List<HSSFPictureData> getAllPictures()
  1415. {
  1416. // The drawing group record always exists at the top level, so we won't need to do this recursively.
  1417. List<HSSFPictureData> pictures = new ArrayList<HSSFPictureData>();
  1418. Iterator<Record> recordIter = workbook.getRecords().iterator();
  1419. while (recordIter.hasNext())
  1420. {
  1421. Record r = recordIter.next();
  1422. if (r instanceof AbstractEscherHolderRecord)
  1423. {
  1424. ((AbstractEscherHolderRecord) r).decode();
  1425. List<EscherRecord> escherRecords = ((AbstractEscherHolderRecord) r).getEscherRecords();
  1426. searchForPictures(escherRecords, pictures);
  1427. }
  1428. }
  1429. return pictures;
  1430. }
  1431. /**
  1432. * Performs a recursive search for pictures in the given list of escher records.
  1433. *
  1434. * @param escherRecords the escher records.
  1435. * @param pictures the list to populate with the pictures.
  1436. */
  1437. private void searchForPictures(List<EscherRecord> escherRecords, List<HSSFPictureData> pictures)
  1438. {
  1439. for(EscherRecord escherRecord : escherRecords) {
  1440. if (escherRecord instanceof EscherBSERecord)
  1441. {
  1442. EscherBlipRecord blip = ((EscherBSERecord) escherRecord).getBlipRecord();
  1443. if (blip != null)
  1444. {
  1445. // TODO: Some kind of structure.
  1446. HSSFPictureData picture = new HSSFPictureData(blip);
  1447. pictures.add(picture);
  1448. }
  1449. }
  1450. // Recursive call.
  1451. searchForPictures(escherRecord.getChildRecords(), pictures);
  1452. }
  1453. }
  1454. /**
  1455. * Is the workbook protected with a password (not encrypted)?
  1456. */
  1457. public boolean isWriteProtected() {
  1458. return this.workbook.isWriteProtected();
  1459. }
  1460. /**
  1461. * protect a workbook with a password (not encypted, just sets writeprotect
  1462. * flags and the password.
  1463. * @param password to set
  1464. */
  1465. public void writeProtectWorkbook( String password, String username ) {
  1466. this.workbook.writeProtectWorkbook(password, username);
  1467. }
  1468. /**
  1469. * removes the write protect flag
  1470. */
  1471. public void unwriteProtectWorkbook() {
  1472. this.workbook.unwriteProtectWorkbook();
  1473. }
  1474. /**
  1475. * Gets all embedded OLE2 objects from the Workbook.
  1476. *
  1477. * @return the list of embedded objects (a list of {@link HSSFObjectData} objects.)
  1478. */
  1479. public List<HSSFObjectData> getAllEmbeddedObjects()
  1480. {
  1481. List<HSSFObjectData> objects = new ArrayList<HSSFObjectData>();
  1482. for (int i = 0; i < getNumberOfSheets(); i++)
  1483. {
  1484. getAllEmbeddedObjects(getSheetAt(i).getSheet().getRecords(), objects);
  1485. }
  1486. return objects;
  1487. }
  1488. /**
  1489. * Gets all embedded OLE2 objects from the Workbook.
  1490. *
  1491. * @param records the list of records to search.
  1492. * @param objects the list of embedded objects to populate.
  1493. */
  1494. private void getAllEmbeddedObjects(List<RecordBase> records, List<HSSFObjectData> objects)
  1495. {
  1496. for (RecordBase obj : records) {
  1497. if (obj instanceof ObjRecord)
  1498. {
  1499. // TODO: More convenient way of determining if there is stored binary.
  1500. // TODO: Link to the data stored in the other stream.
  1501. Iterator<SubRecord> subRecordIter = ((ObjRecord) obj).getSubRecords().iterator();
  1502. while (subRecordIter.hasNext())
  1503. {
  1504. SubRecord sub = subRecordIter.next();
  1505. if (sub instanceof EmbeddedObjectRefSubRecord)
  1506. {
  1507. objects.add(new HSSFObjectData((ObjRecord) obj, directory));
  1508. }
  1509. }
  1510. }
  1511. }
  1512. }
  1513. public HSSFCreationHelper getCreationHelper() {
  1514. return new HSSFCreationHelper(this);
  1515. }
  1516. /**
  1517. *
  1518. * Returns the locator of user-defined functions.
  1519. * The default instance extends the built-in functions with the Analysis Tool Pack
  1520. *
  1521. * @return the locator of user-defined functions
  1522. */
  1523. /*package*/ UDFFinder getUDFFinder(){
  1524. return _udfFinder;
  1525. }
  1526. /**
  1527. * Register a new toolpack in this workbook.
  1528. *
  1529. * @param toopack the toolpack to register
  1530. */
  1531. public void addToolPack(UDFFinder toopack){
  1532. AggregatingUDFFinder udfs = (AggregatingUDFFinder)_udfFinder;
  1533. udfs.add(toopack);
  1534. }
  1535. /**
  1536. * Whether the application shall perform a full recalculation when the workbook is opened.
  1537. * <p>
  1538. * Typically you want to force formula recalculation when you modify cell formulas or values
  1539. * of a workbook previously created by Excel. When set to true, this flag will tell Excel
  1540. * that it needs to recalculate all formulas in the workbook the next time the file is opened.
  1541. * </p>
  1542. * <p>
  1543. * Note, that recalculation updates cached formula results and, thus, modifies the workbook.
  1544. * Depending on the version, Excel may prompt you with "Do you want to save the changes in <em>filename</em>?"
  1545. * on close.
  1546. * </p>
  1547. *
  1548. * @param value true if the application will perform a full recalculation of
  1549. * workbook values when the workbook is opened
  1550. * @since 3.8
  1551. */
  1552. public void setForceFormulaRecalculation(boolean value){
  1553. InternalWorkbook iwb = getWorkbook();
  1554. RecalcIdRecord recalc = iwb.getRecalcId();
  1555. recalc.setEngineId(0);
  1556. }
  1557. /**
  1558. * Whether Excel will be asked to recalculate all formulas when the workbook is opened.
  1559. *
  1560. * @since 3.8
  1561. */
  1562. public boolean getForceFormulaRecalculation(){
  1563. InternalWorkbook iwb = getWorkbook();
  1564. RecalcIdRecord recalc = (RecalcIdRecord)iwb.findFirstRecordBySid(RecalcIdRecord.sid);
  1565. return recalc != null && recalc.getEngineId() != 0;
  1566. }
  1567. /**
  1568. * Changes an external referenced file to another file.
  1569. * A formular in Excel which refers a cell in another file is saved in two parts:
  1570. * The referenced file is stored in an reference table. the row/cell information is saved separate.
  1571. * This method invokation will only change the reference in the lookup-table itself.
  1572. * @param oldUrl The old URL to search for and which is to be replaced
  1573. * @param newUrl The URL replacement
  1574. * @return true if the oldUrl was found and replaced with newUrl. Otherwise false
  1575. */
  1576. public boolean changeExternalReference(String oldUrl, String newUrl) {
  1577. return workbook.changeExternalReference(oldUrl, newUrl);
  1578. }
  1579. }