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

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