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

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