PageRenderTime 55ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/components/forks/poi/src/loci/poi/hssf/usermodel/HSSFWorkbook.java

http://github.com/openmicroscopy/bioformats
Java | 1444 lines | 750 code | 208 blank | 486 comment | 137 complexity | 4f7b036daf89776dc4ee4606b7972144 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, Apache-2.0, BSD-2-Clause, MPL-2.0-no-copyleft-exception
  1. /*
  2. * #%L
  3. * Fork of Apache Jakarta POI.
  4. * %%
  5. * Copyright (C) 2008 - 2013 Open Microscopy Environment:
  6. * - Board of Regents of the University of Wisconsin-Madison
  7. * - Glencoe Software, Inc.
  8. * - University of Dundee
  9. * %%
  10. * Licensed under the Apache License, Version 2.0 (the "License");
  11. * you may not use this file except in compliance with the License.
  12. * You may obtain a copy of the License at
  13. *
  14. * http://www.apache.org/licenses/LICENSE-2.0
  15. *
  16. * Unless required by applicable law or agreed to in writing, software
  17. * distributed under the License is distributed on an "AS IS" BASIS,
  18. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. * See the License for the specific language governing permissions and
  20. * limitations under the License.
  21. * #L%
  22. */
  23. /* ====================================================================
  24. Licensed to the Apache Software Foundation (ASF) under one or more
  25. contributor license agreements. See the NOTICE file distributed with
  26. this work for additional information regarding copyright ownership.
  27. The ASF licenses this file to You under the Apache License, Version 2.0
  28. (the "License"); you may not use this file except in compliance with
  29. the License. You may obtain a copy of the License at
  30. http://www.apache.org/licenses/LICENSE-2.0
  31. Unless required by applicable law or agreed to in writing, software
  32. distributed under the License is distributed on an "AS IS" BASIS,
  33. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  34. See the License for the specific language governing permissions and
  35. limitations under the License.
  36. ==================================================================== */
  37. /*
  38. * HSSFWorkbook.java
  39. *
  40. * Created on September 30, 2001, 3:37 PM
  41. */
  42. package loci.poi.hssf.usermodel;
  43. import loci.common.*;
  44. import loci.poi.POIDocument;
  45. import loci.poi.ddf.EscherBSERecord;
  46. import loci.poi.ddf.EscherBitmapBlip;
  47. import loci.poi.ddf.EscherRecord;
  48. import loci.poi.ddf.EscherBlipRecord;
  49. import loci.poi.hssf.eventmodel.EventRecordFactory;
  50. import loci.poi.hssf.model.Sheet;
  51. import loci.poi.hssf.model.Workbook;
  52. import loci.poi.hssf.record.*;
  53. import loci.poi.hssf.record.formula.Area3DPtg;
  54. import loci.poi.hssf.record.formula.MemFuncPtg;
  55. import loci.poi.hssf.record.formula.UnionPtg;
  56. import loci.poi.hssf.util.CellReference;
  57. import loci.poi.poifs.filesystem.*;
  58. import loci.poi.util.*;
  59. import java.io.ByteArrayInputStream;
  60. import java.io.FileNotFoundException;
  61. import java.io.IOException;
  62. import java.io.InputStream;
  63. import java.io.OutputStream;
  64. import java.io.PrintWriter;
  65. import java.util.ArrayList;
  66. import java.util.Iterator;
  67. import java.util.List;
  68. import java.util.Stack;
  69. /**
  70. * High level representation of a workbook. This is the first object most users
  71. * will construct whether they are reading or writing a workbook. It is also the
  72. * top level object for creating new sheets/etc.
  73. *
  74. * @see loci.poi.hssf.model.Workbook
  75. * @see loci.poi.hssf.usermodel.HSSFSheet
  76. * @author Andrew C. Oliver (acoliver at apache dot org)
  77. * @author Glen Stampoultzis (glens at apache.org)
  78. * @author Shawn Laubach (slaubach at apache dot org)
  79. * @version 2.0-pre
  80. */
  81. public class HSSFWorkbook extends POIDocument
  82. {
  83. private static final int DEBUG = POILogger.DEBUG;
  84. /**
  85. * used for compile-time performance/memory optimization. This determines the
  86. * initial capacity for the sheet collection. Its currently set to 3.
  87. * Changing it in this release will decrease performance
  88. * since you're never allowed to have more or less than three sheets!
  89. */
  90. public final static int INITIAL_CAPACITY = 3;
  91. /**
  92. * this is the reference to the low level Workbook object
  93. */
  94. private Workbook workbook;
  95. /**
  96. * this holds the HSSFSheet objects attached to this workbook
  97. */
  98. protected ArrayList sheets;
  99. /**
  100. * this holds the HSSFName objects attached to this workbook
  101. */
  102. private ArrayList names;
  103. /**
  104. * holds whether or not to preserve other nodes in the POIFS. Used
  105. * for macros and embedded objects.
  106. */
  107. private boolean preserveNodes;
  108. /**
  109. * Used to keep track of the data formatter so that all
  110. * createDataFormatter calls return the same one for a given
  111. * book. This ensures that updates from one places is visible
  112. * someplace else.
  113. */
  114. private HSSFDataFormat formatter;
  115. /** Extended windows meta file */
  116. public static final int PICTURE_TYPE_EMF = 2;
  117. /** Windows Meta File */
  118. public static final int PICTURE_TYPE_WMF = 3;
  119. /** Mac PICT format */
  120. public static final int PICTURE_TYPE_PICT = 4;
  121. /** JPEG format */
  122. public static final int PICTURE_TYPE_JPEG = 5;
  123. /** PNG format */
  124. public static final int PICTURE_TYPE_PNG = 6;
  125. /** Device independant bitmap */
  126. public static final int PICTURE_TYPE_DIB = 7;
  127. private static POILogger log = POILogFactory.getLogger(HSSFWorkbook.class);
  128. /**
  129. * Creates new HSSFWorkbook from scratch (start here!)
  130. *
  131. */
  132. public HSSFWorkbook()
  133. {
  134. this(Workbook.createWorkbook());
  135. }
  136. protected HSSFWorkbook( Workbook book )
  137. {
  138. workbook = book;
  139. sheets = new ArrayList( INITIAL_CAPACITY );
  140. names = new ArrayList( INITIAL_CAPACITY );
  141. }
  142. public HSSFWorkbook(POIFSFileSystem fs) throws IOException {
  143. this(fs,true);
  144. }
  145. /**
  146. * given a POI POIFSFileSystem object, read in its Workbook and populate the high and
  147. * low level models. If you're reading in a workbook...start here.
  148. *
  149. * @param fs the POI filesystem that contains the Workbook stream.
  150. * @param preserveNodes whether to preseve other nodes, such as
  151. * macros. This takes more memory, so only say yes if you
  152. * need to. If set, will store all of the POIFSFileSystem
  153. * in memory
  154. * @see loci.poi.poifs.filesystem.POIFSFileSystem
  155. * @exception IOException if the stream cannot be read
  156. */
  157. public HSSFWorkbook(POIFSFileSystem fs, boolean preserveNodes)
  158. throws IOException
  159. {
  160. this.preserveNodes = preserveNodes;
  161. // Read in the HPSF properties
  162. this.filesystem = fs;
  163. readProperties();
  164. // If we're not preserving nodes, don't track the
  165. // POIFS any more
  166. if(! preserveNodes) {
  167. this.filesystem = null;
  168. }
  169. sheets = new ArrayList(INITIAL_CAPACITY);
  170. names = new ArrayList(INITIAL_CAPACITY);
  171. // Normally, the Workbook will be in a POIFS Stream
  172. // called "Workbook". However, some wierd XLS generators
  173. // put theirs in one called "WORKBOOK"
  174. String workbookName = "Workbook";
  175. try {
  176. fs.getRoot().getEntry(workbookName);
  177. // Is the default name
  178. } catch(FileNotFoundException fe) {
  179. // Try the upper case form
  180. try {
  181. workbookName = "WORKBOOK";
  182. fs.getRoot().getEntry(workbookName);
  183. } catch(FileNotFoundException wfe) {
  184. // Doesn't contain it in either form
  185. throw new IllegalArgumentException("The supplied POIFSFileSystem contained neither a 'Workbook' entry, nor a 'WORKBOOK' entry. Is it really an excel file?");
  186. }
  187. }
  188. // Grab the data from the workbook stream, however
  189. // it happens to be spelt.
  190. InputStream stream = fs.createDocumentInputStream(workbookName);
  191. EventRecordFactory factory = new EventRecordFactory();
  192. List records = RecordFactory.createRecords(stream);
  193. workbook = Workbook.createWorkbook(records);
  194. setPropertiesFromWorkbook(workbook);
  195. int recOffset = workbook.getNumRecords();
  196. int sheetNum = 0;
  197. // convert all LabelRecord records to LabelSSTRecord
  198. convertLabelRecords(records, recOffset);
  199. while (recOffset < records.size())
  200. {
  201. Sheet sheet = Sheet.createSheet(records, sheetNum++, recOffset );
  202. recOffset = sheet.getEofLoc()+1;
  203. if (recOffset == 1)
  204. {
  205. break;
  206. }
  207. HSSFSheet hsheet = new HSSFSheet(this, sheet);
  208. sheets.add(hsheet);
  209. // workbook.setSheetName(sheets.size() -1, "Sheet"+sheets.size());
  210. }
  211. for (int i = 0 ; i < workbook.getNumNames() ; ++i){
  212. HSSFName name = new HSSFName(workbook, workbook.getNameRecord(i));
  213. names.add(name);
  214. }
  215. }
  216. public HSSFWorkbook(RandomAccessInputStream s) throws IOException {
  217. this(s,true);
  218. }
  219. /**
  220. * Companion to HSSFWorkbook(POIFSFileSystem), this constructs the POI filesystem around your
  221. * inputstream.
  222. *
  223. * @param s the POI filesystem that contains the Workbook stream.
  224. * @param preserveNodes whether to preseve other nodes, such as
  225. * macros. This takes more memory, so only say yes if you
  226. * need to.
  227. * @see loci.poi.poifs.filesystem.POIFSFileSystem
  228. * @see #HSSFWorkbook(POIFSFileSystem)
  229. * @exception IOException if the stream cannot be read
  230. */
  231. public HSSFWorkbook(RandomAccessInputStream s, boolean preserveNodes)
  232. throws IOException
  233. {
  234. this(new POIFSFileSystem(s, 512), preserveNodes);
  235. }
  236. /**
  237. * used internally to set the workbook properties.
  238. */
  239. private void setPropertiesFromWorkbook(Workbook book)
  240. {
  241. this.workbook = book;
  242. // none currently
  243. }
  244. /**
  245. * This is basically a kludge to deal with the now obsolete Label records. If
  246. * you have to read in a sheet that contains Label records, be aware that the rest
  247. * of the API doesn't deal with them, the low level structure only provides read-only
  248. * semi-immutable structures (the sets are there for interface conformance with NO
  249. * impelmentation). In short, you need to call this function passing it a reference
  250. * to the Workbook object. All labels will be converted to LabelSST records and their
  251. * contained strings will be written to the Shared String tabel (SSTRecord) within
  252. * the Workbook.
  253. *
  254. * @param wb sheet's matching low level Workbook structure containing the SSTRecord.
  255. * @see loci.poi.hssf.record.LabelRecord
  256. * @see loci.poi.hssf.record.LabelSSTRecord
  257. * @see loci.poi.hssf.record.SSTRecord
  258. */
  259. private void convertLabelRecords(List records, int offset)
  260. {
  261. if (log.check( POILogger.DEBUG ))
  262. log.log(POILogger.DEBUG, "convertLabelRecords called");
  263. for (int k = offset; k < records.size(); k++)
  264. {
  265. Record rec = ( Record ) records.get(k);
  266. if (rec.getSid() == LabelRecord.sid)
  267. {
  268. LabelRecord oldrec = ( LabelRecord ) rec;
  269. records.remove(k);
  270. LabelSSTRecord newrec = new LabelSSTRecord();
  271. int stringid =
  272. workbook.addSSTString(new UnicodeString(oldrec.getValue()));
  273. newrec.setRow(oldrec.getRow());
  274. newrec.setColumn(oldrec.getColumn());
  275. newrec.setXFIndex(oldrec.getXFIndex());
  276. newrec.setSSTIndex(stringid);
  277. records.add(k, newrec);
  278. }
  279. }
  280. if (log.check( POILogger.DEBUG ))
  281. log.log(POILogger.DEBUG, "convertLabelRecords exit");
  282. }
  283. /**
  284. * sets the order of appearance for a given sheet.
  285. *
  286. * @param sheetname the name of the sheet to reorder
  287. * @param pos the position that we want to insert the sheet into (0 based)
  288. */
  289. public void setSheetOrder(String sheetname, int pos ) {
  290. sheets.add(pos,sheets.remove(getSheetIndex(sheetname)));
  291. workbook.setSheetOrder(sheetname, pos);
  292. }
  293. /**
  294. * sets the tab whose data is actually seen when the sheet is opened.
  295. * This may be different from the "selected sheet" since excel seems to
  296. * allow you to show the data of one sheet when another is seen "selected"
  297. * in the tabs (at the bottom).
  298. * @see loci.poi.hssf.usermodel.HSSFSheet#setSelected(boolean)
  299. * @param index
  300. */
  301. public void setSelectedTab(short index) {
  302. workbook.getWindowOne().setSelectedTab(index);
  303. }
  304. /**
  305. * gets the tab whose data is actually seen when the sheet is opened.
  306. * This may be different from the "selected sheet" since excel seems to
  307. * allow you to show the data of one sheet when another is seen "selected"
  308. * in the tabs (at the bottom).
  309. * @see loci.poi.hssf.usermodel.HSSFSheet#setSelected(boolean)
  310. */
  311. public short getSelectedTab() {
  312. return workbook.getWindowOne().getSelectedTab();
  313. }
  314. /**
  315. * sets the first tab that is displayed in the list of tabs
  316. * in excel.
  317. * @param index
  318. */
  319. public void setDisplayedTab(short index) {
  320. workbook.getWindowOne().setDisplayedTab(index);
  321. }
  322. /**
  323. * sets the first tab that is displayed in the list of tabs
  324. * in excel.
  325. */
  326. public short getDisplayedTab() {
  327. return workbook.getWindowOne().getDisplayedTab();
  328. }
  329. /**
  330. * @deprecated POI will now properly handle unicode strings without
  331. * forceing an encoding
  332. */
  333. public final static byte ENCODING_COMPRESSED_UNICODE = 0;
  334. /**
  335. * @deprecated POI will now properly handle unicode strings without
  336. * forceing an encoding
  337. */
  338. public final static byte ENCODING_UTF_16 = 1;
  339. /**
  340. * set the sheet name.
  341. * Will throw IllegalArgumentException if the name is greater than 31 chars
  342. * or contains /\?*[]
  343. * @param sheet number (0 based)
  344. */
  345. public void setSheetName(int sheet, String name)
  346. {
  347. if (workbook.doesContainsSheetName( name, sheet ))
  348. throw new IllegalArgumentException( "The workbook already contains a sheet with this name" );
  349. if (sheet > (sheets.size() - 1))
  350. {
  351. throw new RuntimeException("Sheet out of bounds");
  352. }
  353. workbook.setSheetName( sheet, name);
  354. }
  355. /**
  356. * set the sheet name forcing the encoding. Forcing the encoding IS A BAD IDEA!!!
  357. * @deprecated 3-Jan-2006 POI now automatically detects unicode and sets the encoding
  358. * appropriately. Simply use setSheetName(int sheet, String encoding)
  359. * @throws IllegalArgumentException if the name is greater than 31 chars
  360. * or contains /\?*[]
  361. * @param sheet number (0 based)
  362. */
  363. public void setSheetName( int sheet, String name, short encoding )
  364. {
  365. if (workbook.doesContainsSheetName( name, sheet ))
  366. throw new IllegalArgumentException( "The workbook already contains a sheet with this name" );
  367. if (sheet > (sheets.size() - 1))
  368. {
  369. throw new RuntimeException("Sheet out of bounds");
  370. }
  371. switch ( encoding ) {
  372. case ENCODING_COMPRESSED_UNICODE:
  373. case ENCODING_UTF_16:
  374. break;
  375. default:
  376. // TODO java.io.UnsupportedEncodingException
  377. throw new RuntimeException( "Unsupported encoding" );
  378. }
  379. workbook.setSheetName( sheet, name, encoding );
  380. }
  381. /**
  382. * get the sheet name
  383. * @param sheet Number
  384. * @return Sheet name
  385. */
  386. public String getSheetName(int sheet)
  387. {
  388. if (sheet > (sheets.size() - 1))
  389. {
  390. throw new RuntimeException("Sheet out of bounds");
  391. }
  392. return workbook.getSheetName(sheet);
  393. }
  394. /*
  395. * get the sheet's index
  396. * @param name sheet name
  397. * @return sheet index or -1 if it was not found.
  398. */
  399. /** Returns the index of the sheet by his name
  400. * @param name the sheet name
  401. * @return index of the sheet (0 based)
  402. */
  403. public int getSheetIndex(String name)
  404. {
  405. int retval = workbook.getSheetIndex(name);
  406. return retval;
  407. }
  408. /** Returns the index of the given sheet
  409. * @param sheet the sheet to look up
  410. * @return index of the sheet (0 based)
  411. */
  412. public int getSheetIndex(HSSFSheet sheet)
  413. {
  414. for(int i=0; i<sheets.size(); i++) {
  415. if(sheets.get(i) == sheet) {
  416. return i;
  417. }
  418. }
  419. return -1;
  420. }
  421. /**
  422. * create an HSSFSheet for this HSSFWorkbook, adds it to the sheets and returns
  423. * the high level representation. Use this to create new sheets.
  424. *
  425. * @return HSSFSheet representing the new sheet.
  426. */
  427. public HSSFSheet createSheet()
  428. {
  429. // if (getNumberOfSheets() == 3)
  430. // throw new RuntimeException("You cannot have more than three sheets in HSSF 1.0");
  431. HSSFSheet sheet = new HSSFSheet(this);
  432. sheets.add(sheet);
  433. workbook.setSheetName(sheets.size() - 1,
  434. "Sheet" + (sheets.size() - 1));
  435. WindowTwoRecord windowTwo = (WindowTwoRecord) sheet.getSheet().findFirstRecordBySid(WindowTwoRecord.sid);
  436. windowTwo.setSelected(sheets.size() == 1);
  437. windowTwo.setPaged(sheets.size() == 1);
  438. return sheet;
  439. }
  440. /**
  441. * create an HSSFSheet from an existing sheet in the HSSFWorkbook.
  442. *
  443. * @return HSSFSheet representing the cloned sheet.
  444. */
  445. public HSSFSheet cloneSheet(int sheetNum) {
  446. HSSFSheet srcSheet = (HSSFSheet)sheets.get(sheetNum);
  447. String srcName = workbook.getSheetName(sheetNum);
  448. if (srcSheet != null) {
  449. HSSFSheet clonedSheet = srcSheet.cloneSheet(this);
  450. WindowTwoRecord windowTwo = (WindowTwoRecord) clonedSheet.getSheet().findFirstRecordBySid(WindowTwoRecord.sid);
  451. windowTwo.setSelected(sheets.size() == 1);
  452. windowTwo.setPaged(sheets.size() == 1);
  453. sheets.add(clonedSheet);
  454. int i=1;
  455. while (true) {
  456. //Try and find the next sheet name that is unique
  457. String name = srcName;
  458. String index = Integer.toString(i++);
  459. if (name.length()+index.length()+2<31)
  460. name = name + "("+index+")";
  461. else name = name.substring(0, 31-index.length()-2)+"("+index+")";
  462. //If the sheet name is unique, then set it otherwise move on to the next number.
  463. if (workbook.getSheetIndex(name) == -1) {
  464. workbook.setSheetName(sheets.size()-1, name);
  465. break;
  466. }
  467. }
  468. return clonedSheet;
  469. }
  470. return null;
  471. }
  472. /**
  473. * create an HSSFSheet for this HSSFWorkbook, adds it to the sheets and returns
  474. * the high level representation. Use this to create new sheets.
  475. *
  476. * @param sheetname sheetname to set for the sheet.
  477. * @return HSSFSheet representing the new sheet.
  478. */
  479. public HSSFSheet createSheet(String sheetname)
  480. {
  481. if (workbook.doesContainsSheetName( sheetname, sheets.size() ))
  482. throw new IllegalArgumentException( "The workbook already contains a sheet of this name" );
  483. HSSFSheet sheet = new HSSFSheet(this);
  484. sheets.add(sheet);
  485. workbook.setSheetName(sheets.size() - 1, sheetname);
  486. WindowTwoRecord windowTwo = (WindowTwoRecord) sheet.getSheet().findFirstRecordBySid(WindowTwoRecord.sid);
  487. windowTwo.setSelected(sheets.size() == 1);
  488. windowTwo.setPaged(sheets.size() == 1);
  489. return sheet;
  490. }
  491. /**
  492. * get the number of spreadsheets in the workbook (this will be three after serialization)
  493. * @return number of sheets
  494. */
  495. public int getNumberOfSheets()
  496. {
  497. return sheets.size();
  498. }
  499. /**
  500. * Get the HSSFSheet object at the given index.
  501. * @param index of the sheet number (0-based physical & logical)
  502. * @return HSSFSheet at the provided index
  503. */
  504. public HSSFSheet getSheetAt(int index)
  505. {
  506. return (HSSFSheet) sheets.get(index);
  507. }
  508. /**
  509. * Get sheet with the given name
  510. * @param name of the sheet
  511. * @return HSSFSheet with the name provided or null if it does not exist
  512. */
  513. public HSSFSheet getSheet(String name)
  514. {
  515. HSSFSheet retval = null;
  516. for (int k = 0; k < sheets.size(); k++)
  517. {
  518. String sheetname = workbook.getSheetName(k);
  519. if (sheetname.equals(name))
  520. {
  521. retval = (HSSFSheet) sheets.get(k);
  522. }
  523. }
  524. return retval;
  525. }
  526. /**
  527. * removes sheet at the given index
  528. * @param index of the sheet (0-based)
  529. */
  530. public void removeSheetAt(int index)
  531. {
  532. sheets.remove(index);
  533. workbook.removeSheet(index);
  534. }
  535. /**
  536. * determine whether the Excel GUI will backup the workbook when saving.
  537. *
  538. * @param backupValue true to indicate a backup will be performed.
  539. */
  540. public void setBackupFlag(boolean backupValue)
  541. {
  542. BackupRecord backupRecord = workbook.getBackupRecord();
  543. backupRecord.setBackup(backupValue ? (short) 1
  544. : (short) 0);
  545. }
  546. /**
  547. * determine whether the Excel GUI will backup the workbook when saving.
  548. *
  549. * @return the current setting for backups.
  550. */
  551. public boolean getBackupFlag()
  552. {
  553. BackupRecord backupRecord = workbook.getBackupRecord();
  554. return (backupRecord.getBackup() == 0) ? false
  555. : true;
  556. }
  557. /**
  558. * Sets the repeating rows and columns for a sheet (as found in
  559. * File->PageSetup->Sheet). This is function is included in the workbook
  560. * because it creates/modifies name records which are stored at the
  561. * workbook level.
  562. * <p>
  563. * To set just repeating columns:
  564. * <pre>
  565. * workbook.setRepeatingRowsAndColumns(0,0,1,-1-1);
  566. * </pre>
  567. * To set just repeating rows:
  568. * <pre>
  569. * workbook.setRepeatingRowsAndColumns(0,-1,-1,0,4);
  570. * </pre>
  571. * To remove all repeating rows and columns for a sheet.
  572. * <pre>
  573. * workbook.setRepeatingRowsAndColumns(0,-1,-1,-1,-1);
  574. * </pre>
  575. *
  576. * @param sheetIndex 0 based index to sheet.
  577. * @param startColumn 0 based start of repeating columns.
  578. * @param endColumn 0 based end of repeating columns.
  579. * @param startRow 0 based start of repeating rows.
  580. * @param endRow 0 based end of repeating rows.
  581. */
  582. public void setRepeatingRowsAndColumns(int sheetIndex,
  583. int startColumn, int endColumn,
  584. int startRow, int endRow)
  585. {
  586. // Check arguments
  587. if (startColumn == -1 && endColumn != -1) throw new IllegalArgumentException("Invalid column range specification");
  588. if (startRow == -1 && endRow != -1) throw new IllegalArgumentException("Invalid row range specification");
  589. if (startColumn < -1 || startColumn >= 0xFF) throw new IllegalArgumentException("Invalid column range specification");
  590. if (endColumn < -1 || endColumn >= 0xFF) throw new IllegalArgumentException("Invalid column range specification");
  591. if (startRow < -1 || startRow > 65535) throw new IllegalArgumentException("Invalid row range specification");
  592. if (endRow < -1 || endRow > 65535) throw new IllegalArgumentException("Invalid row range specification");
  593. if (startColumn > endColumn) throw new IllegalArgumentException("Invalid column range specification");
  594. if (startRow > endRow) throw new IllegalArgumentException("Invalid row range specification");
  595. HSSFSheet sheet = getSheetAt(sheetIndex);
  596. short externSheetIndex = getWorkbook().checkExternSheet(sheetIndex);
  597. boolean settingRowAndColumn =
  598. startColumn != -1 && endColumn != -1 && startRow != -1 && endRow != -1;
  599. boolean removingRange =
  600. startColumn == -1 && endColumn == -1 && startRow == -1 && endRow == -1;
  601. boolean isNewRecord = false;
  602. NameRecord nameRecord;
  603. nameRecord = findExistingRowColHeaderNameRecord(sheetIndex);
  604. if (removingRange )
  605. {
  606. if (nameRecord != null)
  607. workbook.removeName(findExistingRowColHeaderNameRecordIdx(sheetIndex+1));
  608. return;
  609. }
  610. if ( nameRecord == null )
  611. {
  612. nameRecord = workbook.createBuiltInName(NameRecord.BUILTIN_PRINT_TITLE, sheetIndex+1);
  613. //does a lot of the house keeping for builtin records, like setting lengths to zero etc
  614. isNewRecord = true;
  615. }
  616. short definitionTextLength = settingRowAndColumn ? (short)0x001a : (short)0x000b;
  617. nameRecord.setDefinitionTextLength(definitionTextLength);
  618. Stack ptgs = new Stack();
  619. if (settingRowAndColumn)
  620. {
  621. MemFuncPtg memFuncPtg = new MemFuncPtg();
  622. memFuncPtg.setLenRefSubexpression(23);
  623. ptgs.add(memFuncPtg);
  624. }
  625. if (startColumn >= 0)
  626. {
  627. Area3DPtg area3DPtg1 = new Area3DPtg();
  628. area3DPtg1.setExternSheetIndex(externSheetIndex);
  629. area3DPtg1.setFirstColumn((short)startColumn);
  630. area3DPtg1.setLastColumn((short)endColumn);
  631. area3DPtg1.setFirstRow((short)0);
  632. area3DPtg1.setLastRow((short)0xFFFF);
  633. ptgs.add(area3DPtg1);
  634. }
  635. if (startRow >= 0)
  636. {
  637. Area3DPtg area3DPtg2 = new Area3DPtg();
  638. area3DPtg2.setExternSheetIndex(externSheetIndex);
  639. area3DPtg2.setFirstColumn((short)0);
  640. area3DPtg2.setLastColumn((short)0x00FF);
  641. area3DPtg2.setFirstRow((short)startRow);
  642. area3DPtg2.setLastRow((short)endRow);
  643. ptgs.add(area3DPtg2);
  644. }
  645. if (settingRowAndColumn)
  646. {
  647. UnionPtg unionPtg = new UnionPtg();
  648. ptgs.add(unionPtg);
  649. }
  650. nameRecord.setNameDefinition(ptgs);
  651. if (isNewRecord)
  652. {
  653. HSSFName newName = new HSSFName(workbook, nameRecord);
  654. names.add(newName);
  655. }
  656. HSSFPrintSetup printSetup = sheet.getPrintSetup();
  657. printSetup.setValidSettings(false);
  658. WindowTwoRecord w2 = (WindowTwoRecord) sheet.getSheet().findFirstRecordBySid(WindowTwoRecord.sid);
  659. w2.setPaged(true);
  660. }
  661. private NameRecord findExistingRowColHeaderNameRecord( int sheetIndex )
  662. {
  663. int index = findExistingRowColHeaderNameRecordIdx(sheetIndex);
  664. if (index == -1)
  665. return null;
  666. else
  667. return (NameRecord)workbook.findNextRecordBySid(NameRecord.sid, index);
  668. }
  669. private int findExistingRowColHeaderNameRecordIdx( int sheetIndex )
  670. {
  671. int index = 0;
  672. NameRecord r = null;
  673. while ((r = (NameRecord) workbook.findNextRecordBySid(NameRecord.sid, index)) != null)
  674. {
  675. int indexToSheet = r.getEqualsToIndexToSheet() -1;
  676. if(indexToSheet > -1) { //ignore "GLOBAL" name records
  677. int nameRecordSheetIndex = workbook.getSheetIndexFromExternSheetIndex(indexToSheet);
  678. if (isRowColHeaderRecord( r ) && nameRecordSheetIndex == sheetIndex)
  679. {
  680. return index;
  681. }
  682. }
  683. index++;
  684. }
  685. return -1;
  686. }
  687. private boolean isRowColHeaderRecord( NameRecord r )
  688. {
  689. return r.getOptionFlag() == 0x20 && ("" + ((char)7)).equals(r.getNameText());
  690. }
  691. /**
  692. * create a new Font and add it to the workbook's font table
  693. * @return new font object
  694. */
  695. public HSSFFont createFont()
  696. {
  697. FontRecord font = workbook.createNewFont();
  698. short fontindex = (short) (getNumberOfFonts() - 1);
  699. if (fontindex > 3)
  700. {
  701. fontindex++; // THERE IS NO FOUR!!
  702. }
  703. if(fontindex == Short.MAX_VALUE){
  704. throw new IllegalArgumentException("Maximum number of fonts was exceeded");
  705. }
  706. HSSFFont retval = new HSSFFont(fontindex, font);
  707. return retval;
  708. }
  709. /**
  710. * Finds a font that matches the one with the supplied attributes
  711. */
  712. public HSSFFont findFont(short boldWeight, short color, short fontHeight,
  713. String name, boolean italic, boolean strikeout,
  714. short typeOffset, byte underline)
  715. {
  716. // System.out.println( boldWeight + ", " + color + ", " + fontHeight + ", " + name + ", " + italic + ", " + strikeout + ", " + typeOffset + ", " + underline );
  717. for (short i = 0; i < workbook.getNumberOfFontRecords(); i++)
  718. {
  719. if (i == 4)
  720. continue;
  721. FontRecord font = workbook.getFontRecordAt(i);
  722. HSSFFont hssfFont = new HSSFFont(i, font);
  723. // System.out.println( hssfFont.getBoldweight() + ", " + hssfFont.getColor() + ", " + hssfFont.getFontHeight() + ", " + hssfFont.getFontName() + ", " + hssfFont.getItalic() + ", " + hssfFont.getStrikeout() + ", " + hssfFont.getTypeOffset() + ", " + hssfFont.getUnderline() );
  724. if (hssfFont.getBoldweight() == boldWeight
  725. && hssfFont.getColor() == color
  726. && hssfFont.getFontHeight() == fontHeight
  727. && hssfFont.getFontName().equals(name)
  728. && hssfFont.getItalic() == italic
  729. && hssfFont.getStrikeout() == strikeout
  730. && hssfFont.getTypeOffset() == typeOffset
  731. && hssfFont.getUnderline() == underline)
  732. {
  733. // System.out.println( "Found font" );
  734. return hssfFont;
  735. }
  736. }
  737. // System.out.println( "No font found" );
  738. return null;
  739. }
  740. /**
  741. * get the number of fonts in the font table
  742. * @return number of fonts
  743. */
  744. public short getNumberOfFonts()
  745. {
  746. return (short) workbook.getNumberOfFontRecords();
  747. }
  748. /**
  749. * get the font at the given index number
  750. * @param idx index number
  751. * @return HSSFFont at the index
  752. */
  753. public HSSFFont getFontAt(short idx)
  754. {
  755. FontRecord font = workbook.getFontRecordAt(idx);
  756. HSSFFont retval = new HSSFFont(idx, font);
  757. return retval;
  758. }
  759. /**
  760. * create a new Cell style and add it to the workbook's style table
  761. * @return the new Cell Style object
  762. */
  763. public HSSFCellStyle createCellStyle()
  764. {
  765. ExtendedFormatRecord xfr = workbook.createCellXF();
  766. short index = (short) (getNumCellStyles() - 1);
  767. HSSFCellStyle style = new HSSFCellStyle(index, xfr);
  768. return style;
  769. }
  770. /**
  771. * get the number of styles the workbook contains
  772. * @return count of cell styles
  773. */
  774. public short getNumCellStyles()
  775. {
  776. return (short) workbook.getNumExFormats();
  777. }
  778. /**
  779. * get the cell style object at the given index
  780. * @param idx index within the set of styles
  781. * @return HSSFCellStyle object at the index
  782. */
  783. public HSSFCellStyle getCellStyleAt(short idx)
  784. {
  785. ExtendedFormatRecord xfr = workbook.getExFormatAt(idx);
  786. HSSFCellStyle style = new HSSFCellStyle(idx, xfr);
  787. return style;
  788. }
  789. /**
  790. * Method write - write out this workbook to an Outputstream. Constructs
  791. * a new POI POIFSFileSystem, passes in the workbook binary representation and
  792. * writes it out.
  793. *
  794. * @param stream - the java OutputStream you wish to write the XLS to
  795. *
  796. * @exception IOException if anything can't be written.
  797. * @see loci.poi.poifs.filesystem.POIFSFileSystem
  798. */
  799. public void write(OutputStream stream)
  800. throws IOException
  801. {
  802. byte[] bytes = getBytes();
  803. POIFSFileSystem fs = new POIFSFileSystem();
  804. // For tracking what we've written out, used if we're
  805. // going to be preserving nodes
  806. List excepts = new ArrayList(1);
  807. // Write out the Workbook stream
  808. fs.createDocument(new RandomAccessInputStream(bytes), "Workbook");
  809. // Write out our HPFS properties, if we have them
  810. writeProperties(fs, excepts);
  811. if (preserveNodes) {
  812. // Don't write out the old Workbook, we'll be doing our new one
  813. excepts.add("Workbook");
  814. // If the file had WORKBOOK instead of Workbook, we'll write it
  815. // out correctly shortly, so don't include the old one
  816. excepts.add("WORKBOOK");
  817. // Copy over all the other nodes to our new poifs
  818. copyNodes(this.filesystem,fs,excepts);
  819. }
  820. fs.writeFilesystem(stream);
  821. //poifs.writeFilesystem(stream);
  822. }
  823. /**
  824. * Method getBytes - get the bytes of just the HSSF portions of the XLS file.
  825. * Use this to construct a POI POIFSFileSystem yourself.
  826. *
  827. *
  828. * @return byte[] array containing the binary representation of this workbook and all contained
  829. * sheets, rows, cells, etc.
  830. *
  831. * @see loci.poi.hssf.model.Workbook
  832. * @see loci.poi.hssf.model.Sheet
  833. */
  834. public byte[] getBytes()
  835. {
  836. if (log.check( POILogger.DEBUG ))
  837. log.log(DEBUG, "HSSFWorkbook.getBytes()");
  838. // before getting the workbook size we must tell the sheets that
  839. // serialization is about to occur.
  840. for (int k = 0; k < sheets.size(); k++)
  841. ((HSSFSheet) sheets.get(k)).getSheet().preSerialize();
  842. int wbsize = workbook.getSize();
  843. // log.debug("REMOVEME: old sizing method "+workbook.serialize().length);
  844. // ArrayList sheetbytes = new ArrayList(sheets.size());
  845. int totalsize = wbsize;
  846. for (int k = 0; k < sheets.size(); k++)
  847. {
  848. workbook.setSheetBof(k, totalsize);
  849. totalsize += ((HSSFSheet) sheets.get(k)).getSheet().getSize();
  850. }
  851. /* if (totalsize < 4096)
  852. {
  853. totalsize = 4096;
  854. }*/
  855. byte[] retval = new byte[totalsize];
  856. int pos = workbook.serialize(0, retval);
  857. // System.arraycopy(wb, 0, retval, 0, wb.length);
  858. for (int k = 0; k < sheets.size(); k++)
  859. {
  860. // byte[] sb = (byte[])sheetbytes.get(k);
  861. // System.arraycopy(sb, 0, retval, pos, sb.length);
  862. int len = ((HSSFSheet) sheets.get(k)).getSheet().serialize(pos,
  863. retval);
  864. pos += len; // sb.length;
  865. }
  866. /* for (int k = pos; k < totalsize; k++)
  867. {
  868. retval[k] = 0;
  869. }*/
  870. return retval;
  871. }
  872. /** @deprecated Do not call this method from your applications. Use the methods
  873. * available in the HSSFRow to add string HSSFCells
  874. */
  875. public int addSSTString(String string)
  876. {
  877. return workbook.addSSTString(new UnicodeString(string));
  878. }
  879. /** @deprecated Do not call this method from your applications. Use the methods
  880. * available in the HSSFRow to get string HSSFCells
  881. */
  882. public String getSSTString(int index)
  883. {
  884. return workbook.getSSTString(index).getString();
  885. }
  886. protected Workbook getWorkbook()
  887. {
  888. return workbook;
  889. }
  890. /** gets the total number of named ranges in the workboko
  891. * @return number of named ranges
  892. */
  893. public int getNumberOfNames(){
  894. int result = names.size();
  895. return result;
  896. }
  897. /** gets the Named range
  898. * @param index position of the named range
  899. * @return named range high level
  900. */
  901. public HSSFName getNameAt(int index){
  902. HSSFName result = (HSSFName) names.get(index);
  903. return result;
  904. }
  905. /** gets the named range name
  906. * @param index the named range index (0 based)
  907. * @return named range name
  908. */
  909. public String getNameName(int index){
  910. String result = getNameAt(index).getNameName();
  911. return result;
  912. }
  913. /**
  914. * Sets the printarea for the sheet provided
  915. * <p>
  916. * i.e. Reference = $A$1:$B$2
  917. * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java)
  918. * @param reference Valid name Reference for the Print Area
  919. */
  920. public void setPrintArea(int sheetIndex, String reference)
  921. {
  922. NameRecord name = workbook.getSpecificBuiltinRecord(NameRecord.BUILTIN_PRINT_AREA, sheetIndex+1);
  923. if (name == null)
  924. name = workbook.createBuiltInName(NameRecord.BUILTIN_PRINT_AREA, sheetIndex+1);
  925. //adding one here because 0 indicates a global named region; doesnt make sense for print areas
  926. short externSheetIndex = getWorkbook().checkExternSheet(sheetIndex);
  927. name.setExternSheetNumber(externSheetIndex);
  928. name.setAreaReference(reference);
  929. }
  930. /**
  931. * For the Convenience of Java Programmers maintaining pointers.
  932. * @see #setPrintArea(int, String)
  933. * @param sheetIndex Zero-based sheet index (0 = First Sheet)
  934. * @param startColumn Column to begin printarea
  935. * @param endColumn Column to end the printarea
  936. * @param startRow Row to begin the printarea
  937. * @param endRow Row to end the printarea
  938. */
  939. public void setPrintArea(int sheetIndex, int startColumn, int endColumn,
  940. int startRow, int endRow) {
  941. //using absolute references because they dont get copied and pasted anyway
  942. CellReference cell = new CellReference(startRow, startColumn, true, true);
  943. String reference = cell.toString();
  944. cell = new CellReference(endRow, endColumn, true, true);
  945. reference = reference+":"+cell.toString();
  946. setPrintArea(sheetIndex, reference);
  947. }
  948. /**
  949. * Retrieves the reference for the printarea of the specified sheet, the sheet name is appended to the reference even if it was not specified.
  950. * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java)
  951. * @return String Null if no print area has been defined
  952. */
  953. public String getPrintArea(int sheetIndex)
  954. {
  955. NameRecord name = workbook.getSpecificBuiltinRecord(NameRecord.BUILTIN_PRINT_AREA, sheetIndex+1);
  956. if (name == null) return null;
  957. //adding one here because 0 indicates a global named region; doesnt make sense for print areas
  958. return name.getAreaReference(workbook);
  959. }
  960. /**
  961. * Delete the printarea for the sheet specified
  962. * @param sheetIndex Zero-based sheet index (0 = First Sheet)
  963. */
  964. public void removePrintArea(int sheetIndex) {
  965. getWorkbook().removeBuiltinRecord(NameRecord.BUILTIN_PRINT_AREA, sheetIndex+1);
  966. }
  967. /** creates a new named range and add it to the model
  968. * @return named range high level
  969. */
  970. public HSSFName createName(){
  971. NameRecord nameRecord = workbook.createName();
  972. HSSFName newName = new HSSFName(workbook, nameRecord);
  973. names.add(newName);
  974. return newName;
  975. }
  976. /** gets the named range index by his name
  977. * <i>Note:</i>Excel named ranges are case-insensitive and
  978. * this method performs a case-insensitive search.
  979. *
  980. * @param name named range name
  981. * @return named range index
  982. */
  983. public int getNameIndex(String name)
  984. {
  985. int retval = -1;
  986. for (int k = 0; k < names.size(); k++)
  987. {
  988. String nameName = getNameName(k);
  989. if (nameName.equalsIgnoreCase(name))
  990. {
  991. retval = k;
  992. break;
  993. }
  994. }
  995. return retval;
  996. }
  997. /** remove the named range by his index
  998. * @param index named range index (0 based)
  999. */
  1000. public void removeName(int index){
  1001. names.remove(index);
  1002. workbook.removeName(index);
  1003. }
  1004. /**
  1005. * Returns the instance of HSSFDataFormat for this workbook.
  1006. * @return the HSSFDataFormat object
  1007. * @see loci.poi.hssf.record.FormatRecord
  1008. * @see loci.poi.hssf.record.Record
  1009. */
  1010. public HSSFDataFormat createDataFormat() {
  1011. if (formatter == null)
  1012. formatter = new HSSFDataFormat(workbook);
  1013. return formatter;
  1014. }
  1015. /** remove the named range by his name
  1016. * @param name named range name
  1017. */
  1018. public void removeName(String name){
  1019. int index = getNameIndex(name);
  1020. removeName(index);
  1021. }
  1022. public HSSFPalette getCustomPalette()
  1023. {
  1024. return new HSSFPalette(workbook.getCustomPalette());
  1025. }
  1026. /** Test only. Do not use */
  1027. public void insertChartRecord()
  1028. {
  1029. int loc = workbook.findFirstRecordLocBySid(SSTRecord.sid);
  1030. byte[] data = {
  1031. (byte)0x0F, (byte)0x00, (byte)0x00, (byte)0xF0, (byte)0x52,
  1032. (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
  1033. (byte)0x06, (byte)0xF0, (byte)0x18, (byte)0x00, (byte)0x00,
  1034. (byte)0x00, (byte)0x01, (byte)0x08, (byte)0x00, (byte)0x00,
  1035. (byte)0x02, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x02,
  1036. (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00,
  1037. (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00,
  1038. (byte)0x00, (byte)0x03, (byte)0x00, (byte)0x00, (byte)0x00,
  1039. (byte)0x33, (byte)0x00, (byte)0x0B, (byte)0xF0, (byte)0x12,
  1040. (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xBF, (byte)0x00,
  1041. (byte)0x08, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x81,
  1042. (byte)0x01, (byte)0x09, (byte)0x00, (byte)0x00, (byte)0x08,
  1043. (byte)0xC0, (byte)0x01, (byte)0x40, (byte)0x00, (byte)0x00,
  1044. (byte)0x08, (byte)0x40, (byte)0x00, (byte)0x1E, (byte)0xF1,
  1045. (byte)0x10, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0D,
  1046. (byte)0x00, (byte)0x00, (byte)0x08, (byte)0x0C, (byte)0x00,
  1047. (byte)0x00, (byte)0x08, (byte)0x17, (byte)0x00, (byte)0x00,
  1048. (byte)0x08, (byte)0xF7, (byte)0x00, (byte)0x00, (byte)0x10,
  1049. };
  1050. UnknownRecord r = new UnknownRecord((short)0x00EB, data);
  1051. workbook.getRecords().add(loc, r);
  1052. }
  1053. /**
  1054. * Spits out a list of all the drawing records in the workbook.
  1055. */
  1056. public void dumpDrawingGroupRecords(boolean fat)
  1057. {
  1058. DrawingGroupRecord r = (DrawingGroupRecord) workbook.findFirstRecordBySid( DrawingGroupRecord.sid );
  1059. r.decode();
  1060. List escherRecords = r.getEscherRecords();
  1061. PrintWriter w = new PrintWriter(System.out);
  1062. for ( Iterator iterator = escherRecords.iterator(); iterator.hasNext(); )
  1063. {
  1064. EscherRecord escherRecord = (EscherRecord) iterator.next();
  1065. if (fat)
  1066. System.out.println(escherRecord.toString());
  1067. else
  1068. escherRecord.display(w, 0);
  1069. }
  1070. w.flush();
  1071. }
  1072. /**
  1073. * Adds a picture to the workbook.
  1074. *
  1075. * @param pictureData The bytes of the picture
  1076. * @param format The format of the picture. One of <code>PICTURE_TYPE_*</code>
  1077. *
  1078. * @return the index to this picture (1 based).
  1079. */
  1080. public int addPicture(byte[] pictureData, int format)
  1081. {
  1082. byte[] uid = newUID();
  1083. EscherBitmapBlip blipRecord = new EscherBitmapBlip();
  1084. blipRecord.setRecordId( (short) ( EscherBitmapBlip.RECORD_ID_START + format ) );
  1085. switch (format)
  1086. {
  1087. case PICTURE_TYPE_EMF:
  1088. blipRecord.setOptions(HSSFPictureData.MSOBI_EMF);
  1089. break;
  1090. case PICTURE_TYPE_WMF:
  1091. blipRecord.setOptions(HSSFPictureData.MSOBI_WMF);
  1092. break;
  1093. case PICTURE_TYPE_PICT:
  1094. blipRecord.setOptions(HSSFPictureData.MSOBI_PICT);
  1095. break;
  1096. case PICTURE_TYPE_PNG:
  1097. blipRecord.setOptions(HSSFPictureData.MSOBI_PNG);
  1098. break;
  1099. case HSSFWorkbook.PICTURE_TYPE_JPEG:
  1100. blipRecord.setOptions(HSSFPictureData.MSOBI_JPEG);
  1101. break;
  1102. case HSSFWorkbook.PICTURE_TYPE_DIB:
  1103. blipRecord.setOptions(HSSFPictureData.MSOBI_DIB);
  1104. break;
  1105. }
  1106. blipRecord.setUID( uid );
  1107. blipRecord.setMarker( (byte) 0xFF );
  1108. blipRecord.setPictureData( pictureData );
  1109. EscherBSERecord r = new EscherBSERecord();
  1110. r.setRecordId( EscherBSERecord.RECORD_ID );
  1111. r.setOptions( (short) ( 0x0002 | ( format << 4 ) ) );
  1112. r.setBlipTypeMacOS( (byte) format );
  1113. r.setBlipTypeWin32( (byte) format );
  1114. r.setUid( uid );
  1115. r.setTag( (short) 0xFF );
  1116. r.setSize( pictureData.length + 25 );
  1117. r.setRef( 1 );
  1118. r.setOffset( 0 );
  1119. r.setBlipRecord( blipRecord );
  1120. return workbook.addBSERecord( r );
  1121. }
  1122. /**
  1123. * Gets all pictures from the Workbook.
  1124. *
  1125. * @return the list of pictures (a list of {@link HSSFPictureData} objects.)
  1126. */
  1127. public List getAllPictures()
  1128. {
  1129. // The drawing group record always exists at the top level, so we won't need to do this recursively.
  1130. List pictures = new ArrayList();
  1131. Iterator recordIter = workbook.getRecords().iterator();
  1132. while (recordIter.hasNext())
  1133. {
  1134. Object obj = recordIter.next();
  1135. if (obj instanceof AbstractEscherHolderRecord)
  1136. {
  1137. ((AbstractEscherHolderRecord) obj).decode();
  1138. List escherRecords = ((AbstractEscherHolderRecord) obj).getEscherRecords();
  1139. searchForPictures(escherRecords, pictures);
  1140. }
  1141. }
  1142. return pictures;
  1143. }
  1144. /**
  1145. * Performs a recursive search for pictures in the given list of escher records.
  1146. *
  1147. * @param escherRecords the escher records.
  1148. * @param pictures the list to populate with the pictures.
  1149. */
  1150. private void searchForPictures(List escherRecords, List pictures)
  1151. {
  1152. Iterator recordIter = escherRecords.iterator();
  1153. while (recordIter.hasNext())
  1154. {
  1155. Object obj = recordIter.next();
  1156. if (obj instanceof EscherRecord)
  1157. {
  1158. EscherRecord escherRecord = (EscherRecord) obj;
  1159. if (escherRecord instanceof EscherBSERecord)
  1160. {
  1161. EscherBlipRecord blip = ((EscherBSERecord) escherRecord).getBlipRecord();
  1162. if (blip != null)
  1163. {
  1164. // TODO: Some kind of structure.
  1165. pictures.add(new HSSFPictureData(blip));
  1166. }
  1167. }
  1168. // Recursive call.
  1169. searchForPictures(escherRecord.getChildRecords(), pictures);
  1170. }
  1171. }
  1172. }
  1173. /**
  1174. * protect a workbook with a password (not encypted, just sets writeprotect
  1175. * flags and the password.
  1176. * @param password to set
  1177. */
  1178. public void writeProtectWorkbook( String password, String username ) {
  1179. this.workbook.writeProtectWorkbook(password, username);
  1180. }
  1181. /**
  1182. * removes the write protect flag
  1183. */
  1184. public void unwriteProtectWorkbook() {
  1185. this.workbook.unwriteProtectWorkbook();
  1186. }
  1187. /**
  1188. * Gets all embedded OLE2 objects from the Workbook.
  1189. *
  1190. * @return the list of embedded objects (a list of {@link HSSFObjectData} objects.)
  1191. */
  1192. public List getAllEmbeddedObjects()
  1193. {
  1194. List objects = new ArrayList();
  1195. for (int i = 0; i < getNumberOfSheets(); i++)
  1196. {
  1197. getAllEmbeddedObjects(getSheetAt(i).getSheet().getRecords(), objects);
  1198. }
  1199. return objects;
  1200. }
  1201. /**
  1202. * Gets all embedded OLE2 objects from the Workbook.
  1203. *
  1204. * @param records the list of records to search.
  1205. * @param objects the list of embedded objects to populate.
  1206. */
  1207. private void getAllEmbeddedObjects(List records, List objects)
  1208. {
  1209. Iterator recordIter = records.iterator();
  1210. while (recordIter.hasNext())
  1211. {
  1212. Object obj = recordIter.next();
  1213. if (obj instanceof ObjRecord)
  1214. {
  1215. // TODO: More convenient way of determining if there is stored binary.
  1216. // TODO: Link to the data stored in the other stream.
  1217. Iterator subRecordIter = ((ObjRecord) obj).getSubRecords().iterator();
  1218. while (subRecordIter.hasNext())
  1219. {
  1220. Object sub = subRecordIter.next();
  1221. if (sub instanceof EmbeddedObjectRefSubRecord)
  1222. {
  1223. objects.add(new HSSFObjectData((ObjRecord) obj, filesystem));
  1224. }
  1225. }
  1226. }
  1227. }
  1228. }
  1229. private byte[] newUID()
  1230. {
  1231. byte[] bytes = new byte[16];
  1232. return bytes;
  1233. }
  1234. }