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

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