Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

HSSFWorkbook.java 72KB

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