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

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