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

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