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

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