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

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