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

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