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.

XSSFWorkbook.java 84KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431
  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.xssf.usermodel;
  16. import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
  17. import static org.apache.poi.xssf.usermodel.helpers.XSSFPasswordHelper.setPassword;
  18. import static org.apache.poi.xssf.usermodel.helpers.XSSFPasswordHelper.validatePassword;
  19. import java.io.ByteArrayInputStream;
  20. import java.io.ByteArrayOutputStream;
  21. import java.io.File;
  22. import java.io.IOException;
  23. import java.io.InputStream;
  24. import java.io.OutputStream;
  25. import java.util.ArrayList;
  26. import java.util.Collection;
  27. import java.util.Collections;
  28. import java.util.HashMap;
  29. import java.util.Iterator;
  30. import java.util.LinkedList;
  31. import java.util.List;
  32. import java.util.Locale;
  33. import java.util.Map;
  34. import java.util.NoSuchElementException;
  35. import java.util.regex.Pattern;
  36. import javax.xml.namespace.QName;
  37. import org.apache.commons.collections4.ListValuedMap;
  38. import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
  39. import org.apache.poi.ooxml.POIXMLDocument;
  40. import org.apache.poi.ooxml.POIXMLDocumentPart;
  41. import org.apache.poi.ooxml.POIXMLException;
  42. import org.apache.poi.ooxml.POIXMLProperties;
  43. import org.apache.poi.hpsf.ClassIDPredefined;
  44. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  45. import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
  46. import org.apache.poi.openxml4j.opc.OPCPackage;
  47. import org.apache.poi.openxml4j.opc.PackageAccess;
  48. import org.apache.poi.openxml4j.opc.PackagePart;
  49. import org.apache.poi.openxml4j.opc.PackagePartName;
  50. import org.apache.poi.openxml4j.opc.PackageRelationship;
  51. import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
  52. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  53. import org.apache.poi.openxml4j.opc.TargetMode;
  54. import org.apache.poi.poifs.crypt.HashAlgorithm;
  55. import org.apache.poi.poifs.filesystem.DirectoryNode;
  56. import org.apache.poi.poifs.filesystem.Ole10Native;
  57. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  58. import org.apache.poi.ss.SpreadsheetVersion;
  59. import org.apache.poi.ss.formula.SheetNameFormatter;
  60. import org.apache.poi.ss.formula.udf.AggregatingUDFFinder;
  61. import org.apache.poi.ss.formula.udf.IndexedUDFFinder;
  62. import org.apache.poi.ss.formula.udf.UDFFinder;
  63. import org.apache.poi.ss.usermodel.*;
  64. import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
  65. import org.apache.poi.ss.util.CellReference;
  66. import org.apache.poi.ss.util.WorkbookUtil;
  67. import org.apache.poi.util.Beta;
  68. import org.apache.poi.util.IOUtils;
  69. import org.apache.poi.util.Internal;
  70. import org.apache.poi.util.NotImplemented;
  71. import org.apache.poi.util.POILogFactory;
  72. import org.apache.poi.util.POILogger;
  73. import org.apache.poi.ooxml.util.PackageHelper;
  74. import org.apache.poi.util.Removal;
  75. import org.apache.poi.util.Units;
  76. import org.apache.poi.xssf.XLSBUnsupportedException;
  77. import org.apache.poi.xssf.model.CalculationChain;
  78. import org.apache.poi.xssf.model.ExternalLinksTable;
  79. import org.apache.poi.xssf.model.MapInfo;
  80. import org.apache.poi.xssf.model.SharedStringsTable;
  81. import org.apache.poi.xssf.model.StylesTable;
  82. import org.apache.poi.xssf.model.ThemesTable;
  83. import org.apache.poi.xssf.usermodel.helpers.XSSFFormulaUtils;
  84. import org.apache.xmlbeans.XmlException;
  85. import org.apache.xmlbeans.XmlObject;
  86. import org.apache.xmlbeans.XmlOptions;
  87. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBookView;
  88. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBookViews;
  89. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcPr;
  90. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName;
  91. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedNames;
  92. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDialogsheet;
  93. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTExternalReference;
  94. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotCache;
  95. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotCaches;
  96. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheet;
  97. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheets;
  98. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook;
  99. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookPr;
  100. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookProtection;
  101. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
  102. import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCalcMode;
  103. import org.openxmlformats.schemas.spreadsheetml.x2006.main.STSheetState;
  104. import org.openxmlformats.schemas.spreadsheetml.x2006.main.WorkbookDocument;
  105. /**
  106. * High level representation of a SpreadsheetML workbook. This is the first object most users
  107. * will construct whether they are reading or writing a workbook. It is also the
  108. * top level object for creating new sheets/etc.
  109. */
  110. public class XSSFWorkbook extends POIXMLDocument implements Workbook, Date1904Support {
  111. private static final Pattern COMMA_PATTERN = Pattern.compile(",");
  112. /**
  113. * Width of one character of the default font in pixels. Same for Calibri and Arial.
  114. * @deprecated POI 3.17 beta 1
  115. * @see Units#DEFAULT_CHARACTER_WIDTH
  116. */
  117. @Removal(version="4.1")
  118. public static final float DEFAULT_CHARACTER_WIDTH = Units.DEFAULT_CHARACTER_WIDTH;
  119. /**
  120. * Excel silently truncates long sheet names to 31 chars.
  121. * This constant is used to ensure uniqueness in the first 31 chars
  122. */
  123. private static final int MAX_SENSITIVE_SHEET_NAME_LEN = 31;
  124. /**
  125. * Images formats supported by XSSF but not by HSSF
  126. */
  127. public static final int PICTURE_TYPE_GIF = 8;
  128. public static final int PICTURE_TYPE_TIFF = 9;
  129. public static final int PICTURE_TYPE_EPS = 10;
  130. public static final int PICTURE_TYPE_BMP = 11;
  131. public static final int PICTURE_TYPE_WPG = 12;
  132. /**
  133. * The underlying XML bean
  134. */
  135. private CTWorkbook workbook;
  136. /**
  137. * this holds the XSSFSheet objects attached to this workbook
  138. */
  139. private List<XSSFSheet> sheets;
  140. /**
  141. * this holds the XSSFName objects attached to this workbook, keyed by lower-case name
  142. */
  143. private ListValuedMap<String, XSSFName> namedRangesByName;
  144. /**
  145. * this holds the XSSFName objects attached to this workbook
  146. */
  147. private List<XSSFName> namedRanges;
  148. /**
  149. * shared string table - a cache of strings in this workbook
  150. */
  151. private SharedStringsTable sharedStringSource;
  152. /**
  153. * A collection of shared objects used for styling content,
  154. * e.g. fonts, cell styles, colors, etc.
  155. */
  156. private StylesTable stylesSource;
  157. /**
  158. * The locator of user-defined functions.
  159. * By default includes functions from the Excel Analysis Toolpack
  160. */
  161. private IndexedUDFFinder _udfFinder = new IndexedUDFFinder(AggregatingUDFFinder.DEFAULT);
  162. /**
  163. * TODO
  164. */
  165. private CalculationChain calcChain;
  166. /**
  167. * External Links, for referencing names or cells in other workbooks.
  168. */
  169. private List<ExternalLinksTable> externalLinks;
  170. /**
  171. * A collection of custom XML mappings
  172. */
  173. private MapInfo mapInfo;
  174. /**
  175. * Used to keep track of the data formatter so that all
  176. * createDataFormatter calls return the same one for a given
  177. * book. This ensures that updates from one places is visible
  178. * someplace else.
  179. */
  180. private XSSFDataFormat formatter;
  181. /**
  182. * The policy to apply in the event of missing or
  183. * blank cells when fetching from a row.
  184. * See {@link org.apache.poi.ss.usermodel.Row.MissingCellPolicy}
  185. */
  186. private MissingCellPolicy _missingCellPolicy = MissingCellPolicy.RETURN_NULL_AND_BLANK;
  187. /**
  188. * Whether a call to {@link XSSFCell#setCellFormula(String)} will validate the formula or not.
  189. */
  190. private boolean cellFormulaValidation = true;
  191. /**
  192. * array of pictures for this workbook
  193. */
  194. private List<XSSFPictureData> pictures;
  195. private static POILogger logger = POILogFactory.getLogger(XSSFWorkbook.class);
  196. /**
  197. * cached instance of XSSFCreationHelper for this workbook
  198. * @see #getCreationHelper()
  199. */
  200. private XSSFCreationHelper _creationHelper;
  201. /**
  202. * List of all pivot tables in workbook
  203. */
  204. private List<XSSFPivotTable> pivotTables;
  205. private List<CTPivotCache> pivotCaches;
  206. private final XSSFFactory xssfFactory;
  207. /**
  208. * Create a new SpreadsheetML workbook.
  209. */
  210. public XSSFWorkbook() {
  211. this(XSSFWorkbookType.XLSX);
  212. }
  213. public XSSFWorkbook(XSSFFactory factory) {
  214. this(XSSFWorkbookType.XLSX, factory);
  215. }
  216. /**
  217. * Create a new SpreadsheetML workbook.
  218. * @param workbookType The type of workbook to make (.xlsx or .xlsm).
  219. */
  220. public XSSFWorkbook(XSSFWorkbookType workbookType) {
  221. this(workbookType, null);
  222. }
  223. private XSSFWorkbook(XSSFWorkbookType workbookType, XSSFFactory factory) {
  224. super(newPackage(workbookType));
  225. this.xssfFactory = (factory == null) ? XSSFFactory.getInstance() : factory;
  226. onWorkbookCreate();
  227. }
  228. /**
  229. * Constructs a XSSFWorkbook object given a OpenXML4J <code>Package</code> object,
  230. * see <a href="http://poi.apache.org/oxml4j/">http://poi.apache.org/oxml4j/</a>.
  231. *
  232. * <p>Once you have finished working with the Workbook, you should close the package
  233. * by calling either {@link #close()} or {@link OPCPackage#close()}, to avoid
  234. * leaving file handles open.
  235. *
  236. * <p>Creating a XSSFWorkbook from a file-backed OPC Package has a lower memory
  237. * footprint than an InputStream backed one.
  238. *
  239. * @param pkg the OpenXML4J <code>OPC Package</code> object.
  240. */
  241. public XSSFWorkbook(OPCPackage pkg) throws IOException {
  242. super(pkg);
  243. this.xssfFactory = XSSFFactory.getInstance();
  244. beforeDocumentRead();
  245. // Build a tree of POIXMLDocumentParts, this workbook being the root
  246. load(this.xssfFactory);
  247. // some broken Workbooks miss this...
  248. setBookViewsIfMissing();
  249. }
  250. /**
  251. * Constructs a XSSFWorkbook object, by buffering the whole stream into memory
  252. * and then opening an {@link OPCPackage} object for it.
  253. *
  254. * <p>Using an {@link InputStream} requires more memory than using a File, so
  255. * if a {@link File} is available then you should instead do something like
  256. * <pre><code>
  257. * OPCPackage pkg = OPCPackage.open(path);
  258. * XSSFWorkbook wb = new XSSFWorkbook(pkg);
  259. * // work with the wb object
  260. * ......
  261. * pkg.close(); // gracefully closes the underlying zip file
  262. * </code></pre>
  263. */
  264. public XSSFWorkbook(InputStream is) throws IOException {
  265. this(PackageHelper.open(is));
  266. }
  267. /**
  268. * Constructs a XSSFWorkbook object from a given file.
  269. *
  270. * <p>Once you have finished working with the Workbook, you should close
  271. * the package by calling {@link #close()}, to avoid leaving file
  272. * handles open.
  273. *
  274. * <p>Opening a XSSFWorkbook from a file has a lower memory footprint
  275. * than opening from an InputStream
  276. *
  277. * @param file the file to open
  278. */
  279. public XSSFWorkbook(File file) throws IOException, InvalidFormatException {
  280. this(OPCPackage.open(file));
  281. }
  282. /**
  283. * Constructs a XSSFWorkbook object given a file name.
  284. *
  285. *
  286. * <p>Once you have finished working with the Workbook, you should close
  287. * the package by calling {@link #close()}, to avoid leaving file
  288. * handles open.
  289. *
  290. * <p>Opening a XSSFWorkbook from a file has a lower memory footprint
  291. * than opening from an InputStream
  292. *
  293. * @param path the file name.
  294. */
  295. public XSSFWorkbook(String path) throws IOException {
  296. this(openPackage(path));
  297. }
  298. /**
  299. * Constructs a XSSFWorkbook object using Package Part.
  300. * @param part package part
  301. * @since POI 4.0.0
  302. */
  303. public XSSFWorkbook(PackagePart part) throws IOException {
  304. this(part.getInputStream());
  305. }
  306. protected void beforeDocumentRead() {
  307. // Ensure it isn't a XLSB file, which we don't support
  308. if (getCorePart().getContentType().equals(XSSFRelation.XLSB_BINARY_WORKBOOK.getContentType())) {
  309. throw new XLSBUnsupportedException();
  310. }
  311. // Create arrays for parts attached to the workbook itself
  312. pivotTables = new ArrayList<>();
  313. pivotCaches = new ArrayList<>();
  314. }
  315. @Override
  316. protected void onDocumentRead() throws IOException {
  317. try {
  318. WorkbookDocument doc = WorkbookDocument.Factory.parse(getPackagePart().getInputStream(), DEFAULT_XML_OPTIONS);
  319. this.workbook = doc.getWorkbook();
  320. ThemesTable theme = null;
  321. Map<String, XSSFSheet> shIdMap = new HashMap<>();
  322. Map<String, ExternalLinksTable> elIdMap = new HashMap<>();
  323. for(RelationPart rp : getRelationParts()){
  324. POIXMLDocumentPart p = rp.getDocumentPart();
  325. if(p instanceof SharedStringsTable) {
  326. sharedStringSource = (SharedStringsTable)p;
  327. } else if(p instanceof StylesTable) {
  328. stylesSource = (StylesTable)p;
  329. } else if(p instanceof ThemesTable) {
  330. theme = (ThemesTable)p;
  331. } else if(p instanceof CalculationChain) {
  332. calcChain = (CalculationChain)p;
  333. } else if(p instanceof MapInfo) {
  334. mapInfo = (MapInfo)p;
  335. } else if (p instanceof XSSFSheet) {
  336. shIdMap.put(rp.getRelationship().getId(), (XSSFSheet)p);
  337. } else if (p instanceof ExternalLinksTable) {
  338. elIdMap.put(rp.getRelationship().getId(), (ExternalLinksTable)p);
  339. }
  340. }
  341. boolean packageReadOnly = (getPackage().getPackageAccess() == PackageAccess.READ);
  342. if (stylesSource == null) {
  343. // Create Styles if it is missing
  344. if (packageReadOnly) {
  345. stylesSource = new StylesTable();
  346. } else {
  347. stylesSource = (StylesTable)createRelationship(XSSFRelation.STYLES, this.xssfFactory);
  348. }
  349. }
  350. stylesSource.setWorkbook(this);
  351. stylesSource.setTheme(theme);
  352. if (sharedStringSource == null) {
  353. // Create SST if it is missing
  354. if (packageReadOnly) {
  355. sharedStringSource = new SharedStringsTable();
  356. } else {
  357. sharedStringSource = (SharedStringsTable)createRelationship(XSSFRelation.SHARED_STRINGS, this.xssfFactory);
  358. }
  359. }
  360. // Load individual sheets. The order of sheets is defined by the order
  361. // of CTSheet elements in the workbook
  362. sheets = new ArrayList<>(shIdMap.size());
  363. //noinspection deprecation
  364. for (CTSheet ctSheet : this.workbook.getSheets().getSheetArray()) {
  365. parseSheet(shIdMap, ctSheet);
  366. }
  367. // Load the external links tables. Their order is defined by the order
  368. // of CTExternalReference elements in the workbook
  369. externalLinks = new ArrayList<>(elIdMap.size());
  370. if (this.workbook.isSetExternalReferences()) {
  371. for (CTExternalReference er : this.workbook.getExternalReferences().getExternalReferenceArray()) {
  372. ExternalLinksTable el = elIdMap.get(er.getId());
  373. if(el == null) {
  374. logger.log(POILogger.WARN, "ExternalLinksTable with r:id " + er.getId()+ " was defined, but didn't exist in package, skipping");
  375. continue;
  376. }
  377. externalLinks.add(el);
  378. }
  379. }
  380. // Process the named ranges
  381. reprocessNamedRanges();
  382. } catch (XmlException e) {
  383. throw new POIXMLException(e);
  384. }
  385. }
  386. /**
  387. * Not normally to be called externally, but possibly to be overridden to avoid
  388. * the DOM based parse of large sheets (see examples).
  389. */
  390. public void parseSheet(Map<String, XSSFSheet> shIdMap, CTSheet ctSheet) {
  391. XSSFSheet sh = shIdMap.get(ctSheet.getId());
  392. if(sh == null) {
  393. logger.log(POILogger.WARN, "Sheet with name " + ctSheet.getName() + " and r:id " + ctSheet.getId()+ " was defined, but didn't exist in package, skipping");
  394. return;
  395. }
  396. sh.sheet = ctSheet;
  397. sh.onDocumentRead();
  398. sheets.add(sh);
  399. }
  400. /**
  401. * Create a new CTWorkbook with all values set to default
  402. */
  403. private void onWorkbookCreate() {
  404. workbook = CTWorkbook.Factory.newInstance();
  405. // don't EVER use the 1904 date system
  406. CTWorkbookPr workbookPr = workbook.addNewWorkbookPr();
  407. workbookPr.setDate1904(false);
  408. setBookViewsIfMissing();
  409. workbook.addNewSheets();
  410. POIXMLProperties.ExtendedProperties expProps = getProperties().getExtendedProperties();
  411. expProps.getUnderlyingProperties().setApplication(DOCUMENT_CREATOR);
  412. sharedStringSource = (SharedStringsTable)createRelationship(XSSFRelation.SHARED_STRINGS, this.xssfFactory);
  413. stylesSource = (StylesTable)createRelationship(XSSFRelation.STYLES, this.xssfFactory);
  414. stylesSource.setWorkbook(this);
  415. namedRanges = new ArrayList<>();
  416. namedRangesByName = new ArrayListValuedHashMap<>();
  417. sheets = new ArrayList<>();
  418. pivotTables = new ArrayList<>();
  419. }
  420. private void setBookViewsIfMissing() {
  421. if(!workbook.isSetBookViews()) {
  422. CTBookViews bvs = workbook.addNewBookViews();
  423. CTBookView bv = bvs.addNewWorkbookView();
  424. bv.setActiveTab(0);
  425. }
  426. }
  427. /**
  428. * Create a new SpreadsheetML package and setup the default minimal content
  429. */
  430. protected static OPCPackage newPackage(XSSFWorkbookType workbookType) {
  431. try {
  432. OPCPackage pkg = OPCPackage.create(new ByteArrayOutputStream()); // NOSONAR - we do not want to close this here
  433. // Main part
  434. PackagePartName corePartName = PackagingURIHelper.createPartName(XSSFRelation.WORKBOOK.getDefaultFileName());
  435. // Create main part relationship
  436. pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT);
  437. // Create main document part
  438. pkg.createPart(corePartName, workbookType.getContentType());
  439. pkg.getPackageProperties().setCreatorProperty(DOCUMENT_CREATOR);
  440. return pkg;
  441. } catch (Exception e){
  442. throw new POIXMLException(e);
  443. }
  444. }
  445. /**
  446. * Return the underlying XML bean
  447. *
  448. * @return the underlying CTWorkbook bean
  449. */
  450. @Internal
  451. public CTWorkbook getCTWorkbook() {
  452. return this.workbook;
  453. }
  454. /**
  455. * Adds a picture to the workbook.
  456. *
  457. * @param pictureData The bytes of the picture
  458. * @param format The format of the picture.
  459. *
  460. * @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} .
  461. * @see Workbook#PICTURE_TYPE_EMF
  462. * @see Workbook#PICTURE_TYPE_WMF
  463. * @see Workbook#PICTURE_TYPE_PICT
  464. * @see Workbook#PICTURE_TYPE_JPEG
  465. * @see Workbook#PICTURE_TYPE_PNG
  466. * @see Workbook#PICTURE_TYPE_DIB
  467. * @see #getAllPictures()
  468. */
  469. @Override
  470. public int addPicture(byte[] pictureData, int format) {
  471. int imageNumber = getAllPictures().size() + 1;
  472. XSSFPictureData img = createRelationship(XSSFPictureData.RELATIONS[format], this.xssfFactory, imageNumber, true).getDocumentPart();
  473. try (OutputStream out = img.getPackagePart().getOutputStream()) {
  474. out.write(pictureData);
  475. } catch (IOException e){
  476. throw new POIXMLException(e);
  477. }
  478. pictures.add(img);
  479. return imageNumber - 1;
  480. }
  481. /**
  482. * Adds a picture to the workbook.
  483. *
  484. * @param is The sream to read image from
  485. * @param format The format of the picture.
  486. *
  487. * @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} .
  488. * @see Workbook#PICTURE_TYPE_EMF
  489. * @see Workbook#PICTURE_TYPE_WMF
  490. * @see Workbook#PICTURE_TYPE_PICT
  491. * @see Workbook#PICTURE_TYPE_JPEG
  492. * @see Workbook#PICTURE_TYPE_PNG
  493. * @see Workbook#PICTURE_TYPE_DIB
  494. * @see #getAllPictures()
  495. */
  496. public int addPicture(InputStream is, int format) throws IOException {
  497. int imageNumber = getAllPictures().size() + 1;
  498. XSSFPictureData img = createRelationship(XSSFPictureData.RELATIONS[format], this.xssfFactory, imageNumber, true).getDocumentPart();
  499. try (OutputStream out = img.getPackagePart().getOutputStream()) {
  500. IOUtils.copy(is, out);
  501. }
  502. pictures.add(img);
  503. return imageNumber - 1;
  504. }
  505. /**
  506. * Create an XSSFSheet from an existing sheet in the XSSFWorkbook.
  507. * The cloned sheet is a deep copy of the original.
  508. *
  509. * @param sheetNum The index of the sheet to clone
  510. * @return XSSFSheet representing the cloned sheet.
  511. * @throws IllegalArgumentException if the sheet index in invalid
  512. * @throws POIXMLException if there were errors when cloning
  513. */
  514. @Override
  515. public XSSFSheet cloneSheet(int sheetNum) {
  516. return cloneSheet(sheetNum, null);
  517. }
  518. @Override
  519. public void close() throws IOException {
  520. super.close();
  521. sharedStringSource.close();
  522. }
  523. /**
  524. * Create an XSSFSheet from an existing sheet in the XSSFWorkbook.
  525. * The cloned sheet is a deep copy of the original but with a new given
  526. * name.
  527. *
  528. * @param sheetNum The index of the sheet to clone
  529. * @param newName The name to set for the newly created sheet
  530. * @return XSSFSheet representing the cloned sheet.
  531. * @throws IllegalArgumentException if the sheet index or the sheet
  532. * name is invalid
  533. * @throws POIXMLException if there were errors when cloning
  534. */
  535. public XSSFSheet cloneSheet(int sheetNum, String newName) {
  536. validateSheetIndex(sheetNum);
  537. XSSFSheet srcSheet = sheets.get(sheetNum);
  538. if (newName == null) {
  539. String srcName = srcSheet.getSheetName();
  540. newName = getUniqueSheetName(srcName);
  541. } else {
  542. validateSheetName(newName);
  543. }
  544. XSSFSheet clonedSheet = createSheet(newName);
  545. // copy sheet's relations
  546. List<RelationPart> rels = srcSheet.getRelationParts();
  547. // if the sheet being cloned has a drawing then remember it and re-create it too
  548. XSSFDrawing dg = null;
  549. for(RelationPart rp : rels) {
  550. POIXMLDocumentPart r = rp.getDocumentPart();
  551. // do not copy the drawing relationship, it will be re-created
  552. if(r instanceof XSSFDrawing) {
  553. dg = (XSSFDrawing)r;
  554. continue;
  555. }
  556. addRelation(rp, clonedSheet);
  557. }
  558. try {
  559. for(PackageRelationship pr : srcSheet.getPackagePart().getRelationships()) {
  560. if (pr.getTargetMode() == TargetMode.EXTERNAL) {
  561. clonedSheet.getPackagePart().addExternalRelationship
  562. (pr.getTargetURI().toASCIIString(), pr.getRelationshipType(), pr.getId());
  563. }
  564. }
  565. } catch (InvalidFormatException e) {
  566. throw new POIXMLException("Failed to clone sheet", e);
  567. }
  568. try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
  569. srcSheet.write(out);
  570. try (ByteArrayInputStream bis = new ByteArrayInputStream(out.toByteArray())) {
  571. clonedSheet.read(bis);
  572. }
  573. } catch (IOException e){
  574. throw new POIXMLException("Failed to clone sheet", e);
  575. }
  576. CTWorksheet ct = clonedSheet.getCTWorksheet();
  577. if(ct.isSetLegacyDrawing()) {
  578. logger.log(POILogger.WARN, "Cloning sheets with comments is not yet supported.");
  579. ct.unsetLegacyDrawing();
  580. }
  581. if (ct.isSetPageSetup()) {
  582. logger.log(POILogger.WARN, "Cloning sheets with page setup is not yet supported.");
  583. ct.unsetPageSetup();
  584. }
  585. clonedSheet.setSelected(false);
  586. // clone the sheet drawing along with its relationships
  587. if (dg != null) {
  588. if(ct.isSetDrawing()) {
  589. // unset the existing reference to the drawing,
  590. // so that subsequent call of clonedSheet.createDrawingPatriarch() will create a new one
  591. ct.unsetDrawing();
  592. }
  593. XSSFDrawing clonedDg = clonedSheet.createDrawingPatriarch();
  594. // copy drawing contents
  595. clonedDg.getCTDrawing().set(dg.getCTDrawing());
  596. clonedDg = clonedSheet.createDrawingPatriarch();
  597. // Clone drawing relations
  598. List<RelationPart> srcRels = srcSheet.createDrawingPatriarch().getRelationParts();
  599. for (RelationPart rp : srcRels) {
  600. addRelation(rp, clonedDg);
  601. }
  602. }
  603. return clonedSheet;
  604. }
  605. /**
  606. * @since 3.14-Beta1
  607. */
  608. private static void addRelation(RelationPart rp, POIXMLDocumentPart target) {
  609. PackageRelationship rel = rp.getRelationship();
  610. if (rel.getTargetMode() == TargetMode.EXTERNAL) {
  611. target.getPackagePart().addRelationship(
  612. rel.getTargetURI(), rel.getTargetMode(), rel.getRelationshipType(), rel.getId());
  613. } else {
  614. XSSFRelation xssfRel = XSSFRelation.getInstance(rel.getRelationshipType());
  615. if (xssfRel == null) {
  616. // Don't copy all relations blindly, but only the ones we know about
  617. throw new POIXMLException("Can't clone sheet - unknown relation type found: "+rel.getRelationshipType());
  618. }
  619. target.addRelation(rel.getId(), xssfRel, rp.getDocumentPart());
  620. }
  621. }
  622. /**
  623. * Generate a valid sheet name based on the existing one. Used when cloning sheets.
  624. *
  625. * @param srcName the original sheet name to
  626. * @return clone sheet name
  627. */
  628. private String getUniqueSheetName(String srcName) {
  629. int uniqueIndex = 2;
  630. String baseName = srcName;
  631. int bracketPos = srcName.lastIndexOf('(');
  632. if (bracketPos > 0 && srcName.endsWith(")")) {
  633. String suffix = srcName.substring(bracketPos + 1, srcName.length() - ")".length());
  634. try {
  635. uniqueIndex = Integer.parseInt(suffix.trim());
  636. uniqueIndex++;
  637. baseName = srcName.substring(0, bracketPos).trim();
  638. } catch (NumberFormatException e) {
  639. // contents of brackets not numeric
  640. }
  641. }
  642. while (true) {
  643. // Try and find the next sheet name that is unique
  644. String index = Integer.toString(uniqueIndex++);
  645. String name;
  646. if (baseName.length() + index.length() + 2 < 31) {
  647. name = baseName + " (" + index + ")";
  648. } else {
  649. name = baseName.substring(0, 31 - index.length() - 2) + "(" + index + ")";
  650. }
  651. //If the sheet name is unique, then set it otherwise move on to the next number.
  652. if (getSheetIndex(name) == -1) {
  653. return name;
  654. }
  655. }
  656. }
  657. /**
  658. * Create a new XSSFCellStyle and add it to the workbook's style table
  659. *
  660. * @return the new XSSFCellStyle object
  661. */
  662. @Override
  663. public XSSFCellStyle createCellStyle() {
  664. return stylesSource.createCellStyle();
  665. }
  666. /**
  667. * Returns the workbook's data format table (a factory for creating data format strings).
  668. *
  669. * @return the XSSFDataFormat object
  670. * @see org.apache.poi.ss.usermodel.DataFormat
  671. */
  672. @Override
  673. public XSSFDataFormat createDataFormat() {
  674. if (formatter == null) {
  675. formatter = new XSSFDataFormat(stylesSource);
  676. }
  677. return formatter;
  678. }
  679. /**
  680. * Create a new Font and add it to the workbook's font table
  681. *
  682. * @return new font object
  683. */
  684. @Override
  685. public XSSFFont createFont() {
  686. XSSFFont font = new XSSFFont();
  687. font.registerTo(stylesSource);
  688. return font;
  689. }
  690. @Override
  691. public XSSFName createName() {
  692. CTDefinedName ctName = CTDefinedName.Factory.newInstance();
  693. ctName.setName("");
  694. return createAndStoreName(ctName);
  695. }
  696. private XSSFName createAndStoreName(CTDefinedName ctName) {
  697. XSSFName name = new XSSFName(ctName, this);
  698. namedRanges.add(name);
  699. namedRangesByName.put(ctName.getName().toLowerCase(Locale.ENGLISH), name);
  700. return name;
  701. }
  702. /**
  703. * Create an XSSFSheet for this workbook, adds it to the sheets and returns
  704. * the high level representation. Use this to create new sheets.
  705. *
  706. * @return XSSFSheet representing the new sheet.
  707. */
  708. @Override
  709. public XSSFSheet createSheet() {
  710. String sheetname = "Sheet" + (sheets.size());
  711. int idx = 0;
  712. while(getSheet(sheetname) != null) {
  713. sheetname = "Sheet" + idx;
  714. idx++;
  715. }
  716. return createSheet(sheetname);
  717. }
  718. /**
  719. * Create a new sheet for this Workbook and return the high level representation.
  720. * Use this to create new sheets.
  721. *
  722. * <p>
  723. * Note that Excel allows sheet names up to 31 chars in length but other applications
  724. * (such as OpenOffice) allow more. Some versions of Excel crash with names longer than 31 chars,
  725. * others - truncate such names to 31 character.
  726. * </p>
  727. * <p>
  728. * POI's SpreadsheetAPI silently truncates the input argument to 31 characters.
  729. * Example:
  730. *
  731. * <pre><code>
  732. * Sheet sheet = workbook.createSheet("My very long sheet name which is longer than 31 chars"); // will be truncated
  733. * assert 31 == sheet.getSheetName().length();
  734. * assert "My very long sheet name which i" == sheet.getSheetName();
  735. * </code></pre>
  736. * </p>
  737. *
  738. * Except the 31-character constraint, Excel applies some other rules:
  739. * <p>
  740. * Sheet name MUST be unique in the workbook and MUST NOT contain the any of the following characters:
  741. * <ul>
  742. * <li> 0x0000 </li>
  743. * <li> 0x0003 </li>
  744. * <li> colon (:) </li>
  745. * <li> backslash (\) </li>
  746. * <li> asterisk (*) </li>
  747. * <li> question mark (?) </li>
  748. * <li> forward slash (/) </li>
  749. * <li> opening square bracket ([) </li>
  750. * <li> closing square bracket (]) </li>
  751. * </ul>
  752. * The string MUST NOT begin or end with the single quote (') character.
  753. * </p>
  754. *
  755. * <p>
  756. * See {@link org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)}
  757. * for a safe way to create valid names
  758. * </p>
  759. * @param sheetname sheetname to set for the sheet.
  760. * @return Sheet representing the new sheet.
  761. * @throws IllegalArgumentException if the name is null or invalid
  762. * or workbook already contains a sheet with this name
  763. * @see org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)
  764. */
  765. @Override
  766. public XSSFSheet createSheet(String sheetname) {
  767. if (sheetname == null) {
  768. throw new IllegalArgumentException("sheetName must not be null");
  769. }
  770. validateSheetName(sheetname);
  771. // YK: Mimic Excel and silently truncate sheet names longer than 31 characters
  772. if(sheetname.length() > 31) {
  773. sheetname = sheetname.substring(0, 31);
  774. }
  775. WorkbookUtil.validateSheetName(sheetname);
  776. CTSheet sheet = addSheet(sheetname);
  777. int sheetNumber = 1;
  778. outerloop:
  779. while(true) {
  780. for(XSSFSheet sh : sheets) {
  781. sheetNumber = (int)Math.max(sh.sheet.getSheetId() + 1, sheetNumber);
  782. }
  783. // Bug 57165: We also need to check that the resulting file name is not already taken
  784. // this can happen when moving/cloning sheets
  785. String sheetName = XSSFRelation.WORKSHEET.getFileName(sheetNumber);
  786. for(POIXMLDocumentPart relation : getRelations()) {
  787. if(relation.getPackagePart() != null &&
  788. sheetName.equals(relation.getPackagePart().getPartName().getName())) {
  789. // name is taken => try next one
  790. sheetNumber++;
  791. continue outerloop;
  792. }
  793. }
  794. // no duplicate found => use this one
  795. break;
  796. }
  797. RelationPart rp = createRelationship(XSSFRelation.WORKSHEET, this.xssfFactory, sheetNumber, false);
  798. XSSFSheet wrapper = rp.getDocumentPart();
  799. wrapper.sheet = sheet;
  800. sheet.setId(rp.getRelationship().getId());
  801. sheet.setSheetId(sheetNumber);
  802. if (sheets.isEmpty()) {
  803. wrapper.setSelected(true);
  804. }
  805. sheets.add(wrapper);
  806. return wrapper;
  807. }
  808. private void validateSheetName(final String sheetName) throws IllegalArgumentException {
  809. if (containsSheet( sheetName, sheets.size() )) {
  810. throw new IllegalArgumentException("The workbook already contains a sheet named '" + sheetName + "'");
  811. }
  812. }
  813. protected XSSFDialogsheet createDialogsheet(String sheetname, CTDialogsheet dialogsheet) {
  814. XSSFSheet sheet = createSheet(sheetname);
  815. return new XSSFDialogsheet(sheet);
  816. }
  817. private CTSheet addSheet(String sheetname) {
  818. CTSheet sheet = workbook.getSheets().addNewSheet();
  819. sheet.setName(sheetname);
  820. return sheet;
  821. }
  822. /**
  823. * Finds a font that matches the one with the supplied attributes
  824. *
  825. * @return the font with the matched attributes or <code>null</code>
  826. */
  827. @Override
  828. public XSSFFont findFont(boolean bold, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) {
  829. return stylesSource.findFont(bold, color, fontHeight, name, italic, strikeout, typeOffset, underline);
  830. }
  831. /**
  832. * Convenience method to get the active sheet. The active sheet is is the sheet
  833. * which is currently displayed when the workbook is viewed in Excel.
  834. * 'Selected' sheet(s) is a distinct concept.
  835. */
  836. @Override
  837. public int getActiveSheetIndex() {
  838. //activeTab (Active Sheet Index) Specifies an unsignedInt
  839. //that contains the index to the active sheet in this book view.
  840. return (int)workbook.getBookViews().getWorkbookViewArray(0).getActiveTab();
  841. }
  842. /**
  843. * Gets all pictures from the Workbook.
  844. *
  845. * @return the list of pictures (a list of {@link XSSFPictureData} objects.)
  846. * @see #addPicture(byte[], int)
  847. */
  848. @Override
  849. public List<XSSFPictureData> getAllPictures() {
  850. if(pictures == null){
  851. List<PackagePart> mediaParts = getPackage().getPartsByName(Pattern.compile("/xl/media/.*?"));
  852. pictures = new ArrayList<>(mediaParts.size());
  853. for(PackagePart part : mediaParts){
  854. pictures.add(new XSSFPictureData(part));
  855. }
  856. }
  857. return pictures; //YK: should return Collections.unmodifiableList(pictures);
  858. }
  859. /**
  860. * Get the cell style object at the given index
  861. *
  862. * @param idx index within the set of styles
  863. * @return XSSFCellStyle object at the index
  864. */
  865. @Override
  866. public XSSFCellStyle getCellStyleAt(int idx) {
  867. return stylesSource.getStyleAt(idx);
  868. }
  869. @Override
  870. public XSSFFont getFontAt(short idx) {
  871. return stylesSource.getFontAt(idx);
  872. }
  873. @Override
  874. public XSSFFont getFontAt(int idx) {
  875. return stylesSource.getFontAt(idx);
  876. }
  877. /**
  878. * Get the first named range with the given name.
  879. *
  880. * Note: names of named ranges are not unique as they are scoped by sheet.
  881. * {@link #getNames(String name)} returns all named ranges with the given name.
  882. *
  883. * @param name named range name
  884. * @return XSSFName with the given name. <code>null</code> is returned no named range could be found.
  885. */
  886. @Override
  887. public XSSFName getName(String name) {
  888. Collection<XSSFName> list = getNames(name);
  889. if (list.isEmpty()) {
  890. return null;
  891. }
  892. return list.iterator().next();
  893. }
  894. /**
  895. * Get the named ranges with the given name.
  896. * <i>Note:</i>Excel named ranges are case-insensitive and
  897. * this method performs a case-insensitive search.
  898. *
  899. * @param name named range name
  900. * @return list of XSSFNames with the given name. An empty list if no named ranges could be found
  901. */
  902. @Override
  903. public List<XSSFName> getNames(String name) {
  904. return Collections.unmodifiableList(namedRangesByName.get(name.toLowerCase(Locale.ENGLISH)));
  905. }
  906. /**
  907. * Get the named range at the given index.
  908. *
  909. * @param nameIndex the index of the named range
  910. * @return the XSSFName at the given index
  911. *
  912. * @deprecated 3.16. New projects should avoid accessing named ranges by index.
  913. */
  914. @Override
  915. @Deprecated
  916. public XSSFName getNameAt(int nameIndex) {
  917. int nNames = namedRanges.size();
  918. if (nNames < 1) {
  919. throw new IllegalStateException("There are no defined names in this workbook");
  920. }
  921. if (nameIndex < 0 || nameIndex > nNames) {
  922. throw new IllegalArgumentException("Specified name index " + nameIndex
  923. + " is outside the allowable range (0.." + (nNames-1) + ").");
  924. }
  925. return namedRanges.get(nameIndex);
  926. }
  927. /**
  928. * Get a list of all the named ranges in the workbook.
  929. *
  930. * @return list of XSSFNames in the workbook
  931. */
  932. @Override
  933. public List<XSSFName> getAllNames() {
  934. return Collections.unmodifiableList(namedRanges);
  935. }
  936. /**
  937. * Gets the named range index by name.
  938. *
  939. * @param name named range name
  940. * @return named range index. <code>-1</code> is returned if no named ranges could be found.
  941. *
  942. * @deprecated 3.16. New projects should avoid accessing named ranges by index.
  943. * Use {@link #getName(String)} instead.
  944. */
  945. @Override
  946. @Deprecated
  947. public int getNameIndex(String name) {
  948. XSSFName nm = getName(name);
  949. if (nm != null) {
  950. return namedRanges.indexOf(nm);
  951. }
  952. return -1;
  953. }
  954. /**
  955. * Get the number of styles the workbook contains
  956. *
  957. * @return count of cell styles
  958. */
  959. @Override
  960. public int getNumCellStyles() {
  961. return stylesSource.getNumCellStyles();
  962. }
  963. @Override
  964. public short getNumberOfFonts() {
  965. return (short)getNumberOfFontsAsInt();
  966. }
  967. @Override
  968. public int getNumberOfFontsAsInt() {
  969. return (short)stylesSource.getFonts().size();
  970. }
  971. /**
  972. * Get the number of named ranges in the this workbook
  973. *
  974. * @return number of named ranges
  975. */
  976. @Override
  977. public int getNumberOfNames() {
  978. return namedRanges.size();
  979. }
  980. /**
  981. * Get the number of worksheets in the this workbook
  982. *
  983. * @return number of worksheets
  984. */
  985. @Override
  986. public int getNumberOfSheets() {
  987. return sheets.size();
  988. }
  989. /**
  990. * Retrieves the reference for the printarea of the specified sheet, the sheet name is appended to the reference even if it was not specified.
  991. * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java)
  992. * @return String Null if no print area has been defined
  993. */
  994. @Override
  995. public String getPrintArea(int sheetIndex) {
  996. XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
  997. if (name == null) {
  998. return null;
  999. }
  1000. //adding one here because 0 indicates a global named region; doesnt make sense for print areas
  1001. return name.getRefersToFormula();
  1002. }
  1003. /**
  1004. * Get sheet with the given name (case insensitive match)
  1005. *
  1006. * @param name of the sheet
  1007. * @return XSSFSheet with the name provided or <code>null</code> if it does not exist
  1008. */
  1009. @Override
  1010. public XSSFSheet getSheet(String name) {
  1011. for (XSSFSheet sheet : sheets) {
  1012. if (name.equalsIgnoreCase(sheet.getSheetName())) {
  1013. return sheet;
  1014. }
  1015. }
  1016. return null;
  1017. }
  1018. /**
  1019. * Get the XSSFSheet object at the given index.
  1020. *
  1021. * @param index of the sheet number (0-based physical &amp; logical)
  1022. * @return XSSFSheet at the provided index
  1023. * @throws IllegalArgumentException if the index is out of range (index
  1024. * &lt; 0 || index &gt;= getNumberOfSheets()).
  1025. */
  1026. @Override
  1027. public XSSFSheet getSheetAt(int index) {
  1028. validateSheetIndex(index);
  1029. return sheets.get(index);
  1030. }
  1031. /**
  1032. * Returns the index of the sheet by his name (case insensitive match)
  1033. *
  1034. * @param name the sheet name
  1035. * @return index of the sheet (0 based) or <tt>-1</tt> if not found
  1036. */
  1037. @Override
  1038. public int getSheetIndex(String name) {
  1039. int idx = 0;
  1040. for (XSSFSheet sh : sheets) {
  1041. if (name.equalsIgnoreCase(sh.getSheetName())) {
  1042. return idx;
  1043. }
  1044. idx++;
  1045. }
  1046. return -1;
  1047. }
  1048. /**
  1049. * Returns the index of the given sheet
  1050. *
  1051. * @param sheet the sheet to look up
  1052. * @return index of the sheet (0 based). <tt>-1</tt> if not found
  1053. */
  1054. @Override
  1055. public int getSheetIndex(Sheet sheet) {
  1056. int idx = 0;
  1057. for(XSSFSheet sh : sheets){
  1058. if(sh == sheet) {
  1059. return idx;
  1060. }
  1061. idx++;
  1062. }
  1063. return -1;
  1064. }
  1065. /**
  1066. * Get the sheet name
  1067. *
  1068. * @param sheetIx Number
  1069. * @return Sheet name
  1070. */
  1071. @Override
  1072. public String getSheetName(int sheetIx) {
  1073. validateSheetIndex(sheetIx);
  1074. return sheets.get(sheetIx).getSheetName();
  1075. }
  1076. /**
  1077. * Returns an iterator of the sheets in the workbook
  1078. * in sheet order. Includes hidden and very hidden sheets.
  1079. *
  1080. * Note: remove() is not supported on this iterator.
  1081. * Use {@link #removeSheetAt(int)} to remove sheets instead.
  1082. *
  1083. * @return an iterator of the sheets.
  1084. */
  1085. @Override
  1086. public Iterator<Sheet> sheetIterator() {
  1087. return new SheetIterator<>();
  1088. }
  1089. /**
  1090. * Alias for {@link #sheetIterator()} to allow
  1091. * foreach loops
  1092. *
  1093. * Note: remove() is not supported on this iterator.
  1094. * Use {@link #removeSheetAt(int)} to remove sheets instead.
  1095. *
  1096. * @return an iterator of the sheets.
  1097. */
  1098. @Override
  1099. public Iterator<Sheet> iterator() {
  1100. return sheetIterator();
  1101. }
  1102. private final class SheetIterator<T extends Sheet> implements Iterator<T> {
  1103. final private Iterator<T> it;
  1104. @SuppressWarnings("unchecked")
  1105. public SheetIterator() {
  1106. it = (Iterator<T>) sheets.iterator();
  1107. }
  1108. @Override
  1109. public boolean hasNext() {
  1110. return it.hasNext();
  1111. }
  1112. @Override
  1113. public T next() throws NoSuchElementException {
  1114. return it.next();
  1115. }
  1116. /**
  1117. * Unexpected behavior may occur if sheets are reordered after iterator
  1118. * has been created. Support for the remove method may be added in the future
  1119. * if someone can figure out a reliable implementation.
  1120. */
  1121. @Override
  1122. public void remove() throws IllegalStateException {
  1123. throw new UnsupportedOperationException("remove method not supported on XSSFWorkbook.iterator(). "+
  1124. "Use Sheet.removeSheetAt(int) instead.");
  1125. }
  1126. }
  1127. /**
  1128. * Are we a normal workbook (.xlsx), or a
  1129. * macro enabled workbook (.xlsm)?
  1130. */
  1131. public boolean isMacroEnabled() {
  1132. return getPackagePart().getContentType().equals(XSSFRelation.MACROS_WORKBOOK.getContentType());
  1133. }
  1134. /**
  1135. * Remove the named range at the given index.
  1136. *
  1137. * @param nameIndex the index of the named range name to remove
  1138. *
  1139. * @deprecated 3.16. New projects should use {@link #removeName(Name)}.
  1140. */
  1141. @Override
  1142. @Deprecated
  1143. public void removeName(int nameIndex) {
  1144. removeName(getNameAt(nameIndex));
  1145. }
  1146. /**
  1147. * Remove the first named range found with the given name.
  1148. *
  1149. * Note: names of named ranges are not unique (name + sheet
  1150. * index is unique), so {@link #removeName(Name)} should
  1151. * be used if possible.
  1152. *
  1153. * @param name the named range name to remove
  1154. *
  1155. * @throws IllegalArgumentException if no named range could be found
  1156. *
  1157. * @deprecated 3.16. New projects should use {@link #removeName(Name)}.
  1158. */
  1159. @Override
  1160. @Deprecated
  1161. public void removeName(String name) {
  1162. List<XSSFName> names = namedRangesByName.get(name.toLowerCase(Locale.ENGLISH));
  1163. if (names.isEmpty()) {
  1164. throw new IllegalArgumentException("Named range was not found: " + name);
  1165. }
  1166. removeName(names.get(0));
  1167. }
  1168. /**
  1169. * As {@link #removeName(String)} is not necessarily unique
  1170. * (name + sheet index is unique), this method is more accurate.
  1171. *
  1172. * @param name the name to remove.
  1173. *
  1174. * @throws IllegalArgumentException if the named range is not a part of this XSSFWorkbook
  1175. */
  1176. @Override
  1177. public void removeName(Name name) {
  1178. if (!namedRangesByName.removeMapping(name.getNameName().toLowerCase(Locale.ENGLISH), name)
  1179. || !namedRanges.remove(name)) {
  1180. throw new IllegalArgumentException("Name was not found: " + name);
  1181. }
  1182. }
  1183. void updateName(XSSFName name, String oldName) {
  1184. if (!namedRangesByName.removeMapping(oldName.toLowerCase(Locale.ENGLISH), name)) {
  1185. throw new IllegalArgumentException("Name was not found: " + name);
  1186. }
  1187. namedRangesByName.put(name.getNameName().toLowerCase(Locale.ENGLISH), name);
  1188. }
  1189. /**
  1190. * Delete the printarea for the sheet specified
  1191. *
  1192. * @param sheetIndex 0-based sheet index (0 = First Sheet)
  1193. */
  1194. @Override
  1195. public void removePrintArea(int sheetIndex) {
  1196. XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
  1197. if (name != null) {
  1198. removeName(name);
  1199. }
  1200. }
  1201. /**
  1202. * Removes sheet at the given index.<p>
  1203. *
  1204. * Care must be taken if the removed sheet is the currently active or only selected sheet in
  1205. * the workbook. There are a few situations when Excel must have a selection and/or active
  1206. * sheet. (For example when printing - see Bug 40414).<br>
  1207. *
  1208. * This method makes sure that if the removed sheet was active, another sheet will become
  1209. * active in its place. Furthermore, if the removed sheet was the only selected sheet, another
  1210. * sheet will become selected. The newly active/selected sheet will have the same index, or
  1211. * one less if the removed sheet was the last in the workbook.
  1212. *
  1213. * @param index of the sheet (0-based)
  1214. */
  1215. @Override
  1216. public void removeSheetAt(int index) {
  1217. validateSheetIndex(index);
  1218. onSheetDelete(index);
  1219. XSSFSheet sheet = getSheetAt(index);
  1220. removeRelation(sheet);
  1221. sheets.remove(index);
  1222. // only set new sheet if there are still some left
  1223. if(sheets.size() == 0) {
  1224. return;
  1225. }
  1226. // the index of the closest remaining sheet to the one just deleted
  1227. int newSheetIndex = index;
  1228. if (newSheetIndex >= sheets.size()) {
  1229. newSheetIndex = sheets.size()-1;
  1230. }
  1231. // adjust active sheet
  1232. int active = getActiveSheetIndex();
  1233. if(active == index) {
  1234. // removed sheet was the active one, reset active sheet if there is still one left now
  1235. setActiveSheet(newSheetIndex);
  1236. } else if (active > index) {
  1237. // removed sheet was below the active one => active is one less now
  1238. setActiveSheet(active-1);
  1239. }
  1240. }
  1241. /**
  1242. * Gracefully remove references to the sheet being deleted
  1243. *
  1244. * @param index the 0-based index of the sheet to delete
  1245. */
  1246. private void onSheetDelete(int index) {
  1247. // remove all sheet relations
  1248. final XSSFSheet sheet = getSheetAt(index);
  1249. sheet.onSheetDelete();
  1250. //delete the CTSheet reference from workbook.xml
  1251. workbook.getSheets().removeSheet(index);
  1252. //calculation chain is auxiliary, remove it as it may contain orphan references to deleted cells
  1253. if(calcChain != null) {
  1254. removeRelation(calcChain);
  1255. calcChain = null;
  1256. }
  1257. //adjust indices of names ranges
  1258. List<XSSFName> toRemove = new ArrayList<>();
  1259. for (XSSFName nm : namedRanges) {
  1260. CTDefinedName ct = nm.getCTName();
  1261. if(!ct.isSetLocalSheetId()) {
  1262. continue;
  1263. }
  1264. if (ct.getLocalSheetId() == index) {
  1265. toRemove.add(nm);
  1266. } else if (ct.getLocalSheetId() > index){
  1267. // Bump down by one, so still points at the same sheet
  1268. ct.setLocalSheetId(ct.getLocalSheetId()-1);
  1269. }
  1270. }
  1271. for (XSSFName nm : toRemove) {
  1272. removeName(nm);
  1273. }
  1274. }
  1275. /**
  1276. * Retrieves the current policy on what to do when
  1277. * getting missing or blank cells from a row.
  1278. * The default is to return blank and null cells.
  1279. * {@link MissingCellPolicy}
  1280. */
  1281. @Override
  1282. public MissingCellPolicy getMissingCellPolicy() {
  1283. return _missingCellPolicy;
  1284. }
  1285. /**
  1286. * Sets the policy on what to do when
  1287. * getting missing or blank cells from a row.
  1288. * This will then apply to all calls to
  1289. * {@link Row#getCell(int)}}. See
  1290. * {@link MissingCellPolicy}
  1291. */
  1292. @Override
  1293. public void setMissingCellPolicy(MissingCellPolicy missingCellPolicy) {
  1294. _missingCellPolicy = missingCellPolicy;
  1295. }
  1296. /**
  1297. * Convenience method to set the active sheet. The active sheet is is the sheet
  1298. * which is currently displayed when the workbook is viewed in Excel.
  1299. * 'Selected' sheet(s) is a distinct concept.
  1300. */
  1301. @Override
  1302. public void setActiveSheet(int index) {
  1303. validateSheetIndex(index);
  1304. for (CTBookView arrayBook : workbook.getBookViews().getWorkbookViewArray()) {
  1305. arrayBook.setActiveTab(index);
  1306. }
  1307. }
  1308. /**
  1309. * Validate sheet index
  1310. *
  1311. * @param index the index to validate
  1312. * @throws IllegalArgumentException if the index is out of range (index
  1313. * &lt; 0 || index &gt;= getNumberOfSheets()).
  1314. */
  1315. private void validateSheetIndex(int index) {
  1316. int lastSheetIx = sheets.size() - 1;
  1317. if (index < 0 || index > lastSheetIx) {
  1318. String range = "(0.." + lastSheetIx + ")";
  1319. if (lastSheetIx == -1) {
  1320. range = "(no sheets)";
  1321. }
  1322. throw new IllegalArgumentException("Sheet index ("
  1323. + index +") is out of range " + range);
  1324. }
  1325. }
  1326. /**
  1327. * Gets the first tab that is displayed in the list of tabs in excel.
  1328. *
  1329. * @return integer that contains the index to the active sheet in this book view.
  1330. */
  1331. @Override
  1332. public int getFirstVisibleTab() {
  1333. CTBookViews bookViews = workbook.getBookViews();
  1334. CTBookView bookView = bookViews.getWorkbookViewArray(0);
  1335. return (short) bookView.getFirstSheet();
  1336. }
  1337. /**
  1338. * Sets the first tab that is displayed in the list of tabs in excel.
  1339. *
  1340. * @param index integer that contains the index to the active sheet in this book view.
  1341. */
  1342. @Override
  1343. public void setFirstVisibleTab(int index) {
  1344. CTBookViews bookViews = workbook.getBookViews();
  1345. CTBookView bookView= bookViews.getWorkbookViewArray(0);
  1346. bookView.setFirstSheet(index);
  1347. }
  1348. /**
  1349. * Sets the printarea for the sheet provided
  1350. * <p>
  1351. * i.e. Reference = $A$1:$B$2
  1352. * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java)
  1353. * @param reference Valid name Reference for the Print Area
  1354. */
  1355. @Override
  1356. public void setPrintArea(int sheetIndex, String reference) {
  1357. XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
  1358. if (name == null) {
  1359. name = createBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
  1360. }
  1361. //short externSheetIndex = getWorkbook().checkExternSheet(sheetIndex);
  1362. //name.setExternSheetNumber(externSheetIndex);
  1363. String[] parts = COMMA_PATTERN.split(reference);
  1364. StringBuilder sb = new StringBuilder(32);
  1365. for (int i = 0; i < parts.length; i++) {
  1366. if(i>0) {
  1367. sb.append(',');
  1368. }
  1369. SheetNameFormatter.appendFormat(sb, getSheetName(sheetIndex));
  1370. sb.append('!');
  1371. sb.append(parts[i]);
  1372. }
  1373. name.setRefersToFormula(sb.toString());
  1374. }
  1375. /**
  1376. * For the Convenience of Java Programmers maintaining pointers.
  1377. * @see #setPrintArea(int, String)
  1378. * @param sheetIndex Zero-based sheet index (0 = First Sheet)
  1379. * @param startColumn Column to begin printarea
  1380. * @param endColumn Column to end the printarea
  1381. * @param startRow Row to begin the printarea
  1382. * @param endRow Row to end the printarea
  1383. */
  1384. @Override
  1385. public void setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow) {
  1386. String reference=getReferencePrintArea(getSheetName(sheetIndex), startColumn, endColumn, startRow, endRow);
  1387. setPrintArea(sheetIndex, reference);
  1388. }
  1389. private static String getReferencePrintArea(String sheetName, int startC, int endC, int startR, int endR) {
  1390. //windows excel example: Sheet1!$C$3:$E$4
  1391. CellReference colRef = new CellReference(sheetName, startR, startC, true, true);
  1392. CellReference colRef2 = new CellReference(sheetName, endR, endC, true, true);
  1393. return "$" + colRef.getCellRefParts()[2] + "$" + colRef.getCellRefParts()[1] + ":$" + colRef2.getCellRefParts()[2] + "$" + colRef2.getCellRefParts()[1];
  1394. }
  1395. XSSFName getBuiltInName(String builtInCode, int sheetNumber) {
  1396. for (XSSFName name : namedRangesByName.get(builtInCode.toLowerCase(Locale.ENGLISH))) {
  1397. if (name.getSheetIndex() == sheetNumber) {
  1398. return name;
  1399. }
  1400. }
  1401. return null;
  1402. }
  1403. /**
  1404. * Generates a NameRecord to represent a built-in region
  1405. *
  1406. * @return a new NameRecord
  1407. * @throws IllegalArgumentException if sheetNumber is invalid
  1408. * @throws POIXMLException if such a name already exists in the workbook
  1409. */
  1410. XSSFName createBuiltInName(String builtInName, int sheetNumber) {
  1411. validateSheetIndex(sheetNumber);
  1412. CTDefinedNames names = workbook.getDefinedNames() == null ? workbook.addNewDefinedNames() : workbook.getDefinedNames();
  1413. CTDefinedName nameRecord = names.addNewDefinedName();
  1414. nameRecord.setName(builtInName);
  1415. nameRecord.setLocalSheetId(sheetNumber);
  1416. if (getBuiltInName(builtInName, sheetNumber) != null) {
  1417. throw new POIXMLException("Builtin (" + builtInName
  1418. + ") already exists for sheet (" + sheetNumber + ")");
  1419. }
  1420. return createAndStoreName(nameRecord);
  1421. }
  1422. /**
  1423. * We only set one sheet as selected for compatibility with HSSF.
  1424. */
  1425. @Override
  1426. public void setSelectedTab(int index) {
  1427. int idx = 0;
  1428. for (XSSFSheet sh : sheets) {
  1429. sh.setSelected(idx == index);
  1430. idx++;
  1431. }
  1432. }
  1433. /**
  1434. * Set the sheet name.
  1435. *
  1436. * @param sheetIndex sheet number (0 based)
  1437. * @param sheetname the new sheet name
  1438. * @throws IllegalArgumentException if the name is null or invalid
  1439. * or workbook already contains a sheet with this name
  1440. * @see #createSheet(String)
  1441. * @see org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)
  1442. */
  1443. @Override
  1444. public void setSheetName(int sheetIndex, String sheetname) {
  1445. if (sheetname == null) {
  1446. throw new IllegalArgumentException( "sheetName must not be null" );
  1447. }
  1448. validateSheetIndex(sheetIndex);
  1449. String oldSheetName = getSheetName(sheetIndex);
  1450. // YK: Mimic Excel and silently truncate sheet names longer than 31 characters
  1451. if(sheetname.length() > 31) {
  1452. sheetname = sheetname.substring(0, 31);
  1453. }
  1454. WorkbookUtil.validateSheetName(sheetname);
  1455. // Do nothing if no change
  1456. if (sheetname.equals(oldSheetName)) {
  1457. return;
  1458. }
  1459. // Check it isn't already taken
  1460. if (containsSheet(sheetname, sheetIndex )) {
  1461. throw new IllegalArgumentException( "The workbook already contains a sheet of this name" );
  1462. }
  1463. // Update references to the name
  1464. XSSFFormulaUtils utils = new XSSFFormulaUtils(this);
  1465. utils.updateSheetName(sheetIndex, oldSheetName, sheetname);
  1466. workbook.getSheets().getSheetArray(sheetIndex).setName(sheetname);
  1467. }
  1468. /**
  1469. * sets the order of appearance for a given sheet.
  1470. *
  1471. * @param sheetname the name of the sheet to reorder
  1472. * @param pos the position that we want to insert the sheet into (0 based)
  1473. */
  1474. @Override
  1475. public void setSheetOrder(String sheetname, int pos) {
  1476. int idx = getSheetIndex(sheetname);
  1477. sheets.add(pos, sheets.remove(idx));
  1478. // Reorder CTSheets
  1479. CTSheets ct = workbook.getSheets();
  1480. XmlObject cts = ct.getSheetArray(idx).copy();
  1481. workbook.getSheets().removeSheet(idx);
  1482. CTSheet newcts = ct.insertNewSheet(pos);
  1483. newcts.set(cts);
  1484. //notify sheets
  1485. //noinspection deprecation
  1486. CTSheet[] sheetArray = ct.getSheetArray();
  1487. for(int i=0; i < sheetArray.length; i++) {
  1488. sheets.get(i).sheet = sheetArray[i];
  1489. }
  1490. updateNamedRangesAfterSheetReorder(idx, pos);
  1491. updateActiveSheetAfterSheetReorder(idx, pos);
  1492. }
  1493. /**
  1494. * update sheet-scoped named ranges in this workbook after changing the sheet order
  1495. * of a sheet at oldIndex to newIndex.
  1496. * Sheets between these indices will move left or right by 1.
  1497. *
  1498. * @param oldIndex the original index of the re-ordered sheet
  1499. * @param newIndex the new index of the re-ordered sheet
  1500. */
  1501. private void updateNamedRangesAfterSheetReorder(int oldIndex, int newIndex) {
  1502. // update sheet index of sheet-scoped named ranges
  1503. for (final XSSFName name : namedRanges) {
  1504. final int i = name.getSheetIndex();
  1505. // name has sheet-level scope
  1506. if (i != -1) {
  1507. // name refers to this sheet
  1508. if (i == oldIndex) {
  1509. name.setSheetIndex(newIndex);
  1510. }
  1511. // if oldIndex > newIndex then this sheet moved left and sheets between newIndex and oldIndex moved right
  1512. else if (newIndex <= i && i < oldIndex) {
  1513. name.setSheetIndex(i+1);
  1514. }
  1515. // if oldIndex < newIndex then this sheet moved right and sheets between oldIndex and newIndex moved left
  1516. else if (oldIndex < i && i <= newIndex) {
  1517. name.setSheetIndex(i-1);
  1518. }
  1519. }
  1520. }
  1521. }
  1522. private void updateActiveSheetAfterSheetReorder(int oldIndex, int newIndex) {
  1523. // adjust active sheet if necessary
  1524. int active = getActiveSheetIndex();
  1525. if(active == oldIndex) {
  1526. // moved sheet was the active one
  1527. setActiveSheet(newIndex);
  1528. } else if ((active < oldIndex && active < newIndex) ||
  1529. (active > oldIndex && active > newIndex)) {
  1530. // not affected
  1531. } else if (newIndex > oldIndex) {
  1532. // moved sheet was below before and is above now => active is one less
  1533. setActiveSheet(active-1);
  1534. } else {
  1535. // remaining case: moved sheet was higher than active before and is lower now => active is one more
  1536. setActiveSheet(active+1);
  1537. }
  1538. }
  1539. /**
  1540. * marshal named ranges from the {@link #namedRanges} collection to the underlying CTWorkbook bean
  1541. */
  1542. private void saveNamedRanges(){
  1543. // Named ranges
  1544. if(namedRanges.size() > 0) {
  1545. CTDefinedNames names = CTDefinedNames.Factory.newInstance();
  1546. CTDefinedName[] nr = new CTDefinedName[namedRanges.size()];
  1547. int i = 0;
  1548. for(XSSFName name : namedRanges) {
  1549. nr[i] = name.getCTName();
  1550. i++;
  1551. }
  1552. names.setDefinedNameArray(nr);
  1553. if(workbook.isSetDefinedNames()) {
  1554. workbook.unsetDefinedNames();
  1555. }
  1556. workbook.setDefinedNames(names);
  1557. // Re-process the named ranges
  1558. reprocessNamedRanges();
  1559. } else {
  1560. if(workbook.isSetDefinedNames()) {
  1561. workbook.unsetDefinedNames();
  1562. }
  1563. }
  1564. }
  1565. private void reprocessNamedRanges() {
  1566. namedRangesByName = new ArrayListValuedHashMap<>();
  1567. namedRanges = new ArrayList<>();
  1568. if(workbook.isSetDefinedNames()) {
  1569. for(CTDefinedName ctName : workbook.getDefinedNames().getDefinedNameArray()) {
  1570. createAndStoreName(ctName);
  1571. }
  1572. }
  1573. }
  1574. private void saveCalculationChain(){
  1575. if(calcChain != null){
  1576. int count = calcChain.getCTCalcChain().sizeOfCArray();
  1577. if(count == 0){
  1578. removeRelation(calcChain);
  1579. calcChain = null;
  1580. }
  1581. }
  1582. }
  1583. @Override
  1584. protected void commit() throws IOException {
  1585. saveNamedRanges();
  1586. saveCalculationChain();
  1587. XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
  1588. xmlOptions.setSaveSyntheticDocumentElement(new QName(CTWorkbook.type.getName().getNamespaceURI(), "workbook"));
  1589. PackagePart part = getPackagePart();
  1590. try (OutputStream out = part.getOutputStream()) {
  1591. workbook.save(out, xmlOptions);
  1592. }
  1593. }
  1594. /**
  1595. * Returns SharedStringsTable - tha cache of string for this workbook
  1596. *
  1597. * @return the shared string table
  1598. */
  1599. @Internal
  1600. public SharedStringsTable getSharedStringSource() {
  1601. return this.sharedStringSource;
  1602. }
  1603. /**
  1604. * Return a object representing a collection of shared objects used for styling content,
  1605. * e.g. fonts, cell styles, colors, etc.
  1606. */
  1607. public StylesTable getStylesSource() {
  1608. return this.stylesSource;
  1609. }
  1610. /**
  1611. * Returns the Theme of current workbook.
  1612. */
  1613. public ThemesTable getTheme() {
  1614. if (stylesSource == null) {
  1615. return null;
  1616. }
  1617. return stylesSource.getTheme();
  1618. }
  1619. /**
  1620. * Returns an object that handles instantiating concrete
  1621. * classes of the various instances for XSSF.
  1622. */
  1623. @Override
  1624. public XSSFCreationHelper getCreationHelper() {
  1625. if(_creationHelper == null) {
  1626. _creationHelper = new XSSFCreationHelper(this);
  1627. }
  1628. return _creationHelper;
  1629. }
  1630. /**
  1631. * Determines whether a workbook contains the provided sheet name.
  1632. * For the purpose of comparison, long names are truncated to 31 chars.
  1633. *
  1634. * @param name the name to test (case insensitive match)
  1635. * @param excludeSheetIdx the sheet to exclude from the check or -1 to include all sheets in the check.
  1636. * @return true if the sheet contains the name, false otherwise.
  1637. */
  1638. private boolean containsSheet(String name, int excludeSheetIdx) {
  1639. //noinspection deprecation
  1640. CTSheet[] ctSheetArray = workbook.getSheets().getSheetArray();
  1641. if (name.length() > MAX_SENSITIVE_SHEET_NAME_LEN) {
  1642. name = name.substring(0, MAX_SENSITIVE_SHEET_NAME_LEN);
  1643. }
  1644. for (int i = 0; i < ctSheetArray.length; i++) {
  1645. String ctName = ctSheetArray[i].getName();
  1646. if (ctName.length() > MAX_SENSITIVE_SHEET_NAME_LEN) {
  1647. ctName = ctName.substring(0, MAX_SENSITIVE_SHEET_NAME_LEN);
  1648. }
  1649. if (excludeSheetIdx != i && name.equalsIgnoreCase(ctName)) {
  1650. return true;
  1651. }
  1652. }
  1653. return false;
  1654. }
  1655. /**
  1656. * Gets a boolean value that indicates whether the date systems used in the workbook starts in 1904.
  1657. * <p>
  1658. * The default value is false, meaning that the workbook uses the 1900 date system,
  1659. * where 1/1/1900 is the first day in the system..
  1660. * </p>
  1661. * @return true if the date systems used in the workbook starts in 1904
  1662. */
  1663. @Internal
  1664. @Override
  1665. public boolean isDate1904() {
  1666. CTWorkbookPr workbookPr = workbook.getWorkbookPr();
  1667. return workbookPr != null && workbookPr.getDate1904();
  1668. }
  1669. /**
  1670. * Get the document's embedded files.
  1671. */
  1672. @Override
  1673. public List<PackagePart> getAllEmbeddedParts() throws OpenXML4JException {
  1674. List<PackagePart> embedds = new LinkedList<>();
  1675. for(XSSFSheet sheet : sheets){
  1676. // Get the embeddings for the workbook
  1677. for(PackageRelationship rel : sheet.getPackagePart().getRelationshipsByType(XSSFRelation.OLEEMBEDDINGS.getRelation())) {
  1678. embedds.add( sheet.getPackagePart().getRelatedPart(rel) );
  1679. }
  1680. for(PackageRelationship rel : sheet.getPackagePart().getRelationshipsByType(XSSFRelation.PACKEMBEDDINGS.getRelation())) {
  1681. embedds.add( sheet.getPackagePart().getRelatedPart(rel) );
  1682. }
  1683. }
  1684. return embedds;
  1685. }
  1686. @Override
  1687. @NotImplemented
  1688. public boolean isHidden() {
  1689. throw new RuntimeException("Not implemented yet");
  1690. }
  1691. @Override
  1692. @NotImplemented
  1693. public void setHidden(boolean hiddenFlag) {
  1694. throw new RuntimeException("Not implemented yet");
  1695. }
  1696. @Override
  1697. public boolean isSheetHidden(int sheetIx) {
  1698. validateSheetIndex(sheetIx);
  1699. CTSheet ctSheet = sheets.get(sheetIx).sheet;
  1700. return ctSheet.getState() == STSheetState.HIDDEN;
  1701. }
  1702. @Override
  1703. public boolean isSheetVeryHidden(int sheetIx) {
  1704. validateSheetIndex(sheetIx);
  1705. CTSheet ctSheet = sheets.get(sheetIx).sheet;
  1706. return ctSheet.getState() == STSheetState.VERY_HIDDEN;
  1707. }
  1708. @Override
  1709. public SheetVisibility getSheetVisibility(int sheetIx) {
  1710. validateSheetIndex(sheetIx);
  1711. final CTSheet ctSheet = sheets.get(sheetIx).sheet;
  1712. final STSheetState.Enum state = ctSheet.getState();
  1713. if (state == STSheetState.VISIBLE) {
  1714. return SheetVisibility.VISIBLE;
  1715. }
  1716. if (state == STSheetState.HIDDEN) {
  1717. return SheetVisibility.HIDDEN;
  1718. }
  1719. if (state == STSheetState.VERY_HIDDEN) {
  1720. return SheetVisibility.VERY_HIDDEN;
  1721. }
  1722. throw new IllegalArgumentException("This should never happen");
  1723. }
  1724. @Override
  1725. public void setSheetHidden(int sheetIx, boolean hidden) {
  1726. setSheetVisibility(sheetIx, hidden ? SheetVisibility.HIDDEN : SheetVisibility.VISIBLE);
  1727. }
  1728. @Override
  1729. public void setSheetVisibility(int sheetIx, SheetVisibility visibility) {
  1730. validateSheetIndex(sheetIx);
  1731. final CTSheet ctSheet = sheets.get(sheetIx).sheet;
  1732. switch (visibility) {
  1733. case VISIBLE:
  1734. ctSheet.setState(STSheetState.VISIBLE);
  1735. break;
  1736. case HIDDEN:
  1737. ctSheet.setState(STSheetState.HIDDEN);
  1738. break;
  1739. case VERY_HIDDEN:
  1740. ctSheet.setState(STSheetState.VERY_HIDDEN);
  1741. break;
  1742. default:
  1743. throw new IllegalArgumentException("This should never happen");
  1744. }
  1745. }
  1746. /**
  1747. * Fired when a formula is deleted from this workbook,
  1748. * for example when calling cell.setCellFormula(null)
  1749. *
  1750. * @see XSSFCell#setCellFormula(String)
  1751. */
  1752. protected void onDeleteFormula(XSSFCell cell){
  1753. if(calcChain != null) {
  1754. int sheetId = (int)cell.getSheet().sheet.getSheetId();
  1755. calcChain.removeItem(sheetId, cell.getReference());
  1756. }
  1757. }
  1758. /**
  1759. * Return the {@link CalculationChain} object for this workbook
  1760. * <p>
  1761. * The calculation chain object specifies the order in which the cells in a workbook were last calculated
  1762. * </p>
  1763. *
  1764. * @return the <code>CalculationChain</code> object or <code>null</code> if not defined
  1765. */
  1766. @Internal
  1767. public CalculationChain getCalculationChain() {
  1768. return calcChain;
  1769. }
  1770. /**
  1771. * Returns the list of {@link ExternalLinksTable} object for this workbook
  1772. *
  1773. * <p>The external links table specifies details of named ranges etc
  1774. * that are referenced from other workbooks, along with the last seen
  1775. * values of what they point to.</p>
  1776. *
  1777. * <p>Note that Excel uses index 0 for the current workbook, so the first
  1778. * External Links in a formula would be '[1]Foo' which corresponds to
  1779. * entry 0 in this list.</p>
  1780. * @return the <code>ExternalLinksTable</code> list, which may be empty
  1781. */
  1782. @Internal
  1783. public List<ExternalLinksTable> getExternalLinksTable() {
  1784. return externalLinks;
  1785. }
  1786. /**
  1787. *
  1788. * @return a collection of custom XML mappings defined in this workbook
  1789. */
  1790. public Collection<XSSFMap> getCustomXMLMappings(){
  1791. return mapInfo == null ? new ArrayList<>() : mapInfo.getAllXSSFMaps();
  1792. }
  1793. /**
  1794. *
  1795. * @return the helper class used to query the custom XML mapping defined in this workbook
  1796. */
  1797. @Internal
  1798. public MapInfo getMapInfo(){
  1799. return mapInfo;
  1800. }
  1801. /**
  1802. * Adds the External Link Table part and relations required to allow formulas
  1803. * referencing the specified external workbook to be added to this one. Allows
  1804. * formulas such as "[MyOtherWorkbook.xlsx]Sheet3!$A$5" to be added to the
  1805. * file, for workbooks not already linked / referenced.
  1806. *
  1807. * Note: this is not implemented and thus currently throws an Exception stating this.
  1808. *
  1809. * @param name The name the workbook will be referenced as in formulas
  1810. * @param workbook The open workbook to fetch the link required information from
  1811. *
  1812. * @throws RuntimeException stating that this method is not implemented yet.
  1813. */
  1814. @Override
  1815. @NotImplemented
  1816. public int linkExternalWorkbook(String name, Workbook workbook) {
  1817. throw new RuntimeException("Not Implemented - see bug #57184");
  1818. }
  1819. /**
  1820. * Specifies a boolean value that indicates whether structure of workbook is locked. <br>
  1821. * A value true indicates the structure of the workbook is locked. Worksheets in the workbook can't be moved,
  1822. * deleted, hidden, unhidden, or renamed, and new worksheets can't be inserted.<br>
  1823. * A value of false indicates the structure of the workbook is not locked.<br>
  1824. *
  1825. * @return true if structure of workbook is locked
  1826. */
  1827. public boolean isStructureLocked() {
  1828. return workbookProtectionPresent() && workbook.getWorkbookProtection().getLockStructure();
  1829. }
  1830. /**
  1831. * Specifies a boolean value that indicates whether the windows that comprise the workbook are locked. <br>
  1832. * A value of true indicates the workbook windows are locked. Windows are the same size and position each time the
  1833. * workbook is opened.<br>
  1834. * A value of false indicates the workbook windows are not locked.
  1835. *
  1836. * @return true if windows that comprise the workbook are locked
  1837. */
  1838. public boolean isWindowsLocked() {
  1839. return workbookProtectionPresent() && workbook.getWorkbookProtection().getLockWindows();
  1840. }
  1841. /**
  1842. * Specifies a boolean value that indicates whether the workbook is locked for revisions.
  1843. *
  1844. * @return true if the workbook is locked for revisions.
  1845. */
  1846. public boolean isRevisionLocked() {
  1847. return workbookProtectionPresent() && workbook.getWorkbookProtection().getLockRevision();
  1848. }
  1849. /**
  1850. * Locks the structure of workbook.
  1851. */
  1852. public void lockStructure() {
  1853. safeGetWorkbookProtection().setLockStructure(true);
  1854. }
  1855. /**
  1856. * Unlocks the structure of workbook.
  1857. */
  1858. public void unLockStructure() {
  1859. safeGetWorkbookProtection().setLockStructure(false);
  1860. }
  1861. /**
  1862. * Locks the windows that comprise the workbook.
  1863. */
  1864. public void lockWindows() {
  1865. safeGetWorkbookProtection().setLockWindows(true);
  1866. }
  1867. /**
  1868. * Unlocks the windows that comprise the workbook.
  1869. */
  1870. public void unLockWindows() {
  1871. safeGetWorkbookProtection().setLockWindows(false);
  1872. }
  1873. /**
  1874. * Locks the workbook for revisions.
  1875. */
  1876. public void lockRevision() {
  1877. safeGetWorkbookProtection().setLockRevision(true);
  1878. }
  1879. /**
  1880. * Unlocks the workbook for revisions.
  1881. */
  1882. public void unLockRevision() {
  1883. safeGetWorkbookProtection().setLockRevision(false);
  1884. }
  1885. /**
  1886. * Sets the workbook password.
  1887. *
  1888. * @param password if null, the password will be removed
  1889. * @param hashAlgo if null, the password will be set as XOR password (Excel 2010 and earlier)
  1890. * otherwise the given algorithm is used for calculating the hash password (Excel 2013)
  1891. */
  1892. public void setWorkbookPassword(String password, HashAlgorithm hashAlgo) {
  1893. if (password == null && !workbookProtectionPresent()) {
  1894. return;
  1895. }
  1896. setPassword(safeGetWorkbookProtection(), password, hashAlgo, "workbook");
  1897. }
  1898. /**
  1899. * Validate the password against the stored hash, the hashing method will be determined
  1900. * by the existing password attributes
  1901. * @return true, if the hashes match (... though original password may differ ...)
  1902. */
  1903. public boolean validateWorkbookPassword(String password) {
  1904. if (!workbookProtectionPresent()) {
  1905. return (password == null);
  1906. }
  1907. return validatePassword(safeGetWorkbookProtection(), password, "workbook");
  1908. }
  1909. /**
  1910. * Sets the revisions password.
  1911. *
  1912. * @param password if null, the password will be removed
  1913. * @param hashAlgo if null, the password will be set as XOR password (Excel 2010 and earlier)
  1914. * otherwise the given algorithm is used for calculating the hash password (Excel 2013)
  1915. */
  1916. public void setRevisionsPassword(String password, HashAlgorithm hashAlgo) {
  1917. if (password == null && !workbookProtectionPresent()) {
  1918. return;
  1919. }
  1920. setPassword(safeGetWorkbookProtection(), password, hashAlgo, "revisions");
  1921. }
  1922. /**
  1923. * Validate the password against the stored hash, the hashing method will be determined
  1924. * by the existing password attributes
  1925. * @return true if the hashes match (... though original password may differ ...)
  1926. */
  1927. public boolean validateRevisionsPassword(String password) {
  1928. if (!workbookProtectionPresent()) {
  1929. return (password == null);
  1930. }
  1931. return validatePassword(safeGetWorkbookProtection(), password, "revisions");
  1932. }
  1933. /**
  1934. * Removes the workbook protection settings
  1935. */
  1936. public void unLock() {
  1937. if (workbookProtectionPresent()) {
  1938. workbook.unsetWorkbookProtection();
  1939. }
  1940. }
  1941. private boolean workbookProtectionPresent() {
  1942. return workbook.isSetWorkbookProtection();
  1943. }
  1944. private CTWorkbookProtection safeGetWorkbookProtection() {
  1945. if (!workbookProtectionPresent()){
  1946. return workbook.addNewWorkbookProtection();
  1947. }
  1948. return workbook.getWorkbookProtection();
  1949. }
  1950. /**
  1951. *
  1952. * Returns the locator of user-defined functions.
  1953. * <p>
  1954. * The default instance extends the built-in functions with the Excel Analysis Tool Pack.
  1955. * To set / evaluate custom functions you need to register them as follows:
  1956. *
  1957. *
  1958. *
  1959. * </p>
  1960. * @return wrapped instance of UDFFinder that allows seeking functions both by index and name
  1961. */
  1962. /*package*/ UDFFinder getUDFFinder() {
  1963. return _udfFinder;
  1964. }
  1965. /**
  1966. * Register a new toolpack in this workbook.
  1967. *
  1968. * @param toopack the toolpack to register
  1969. */
  1970. @Override
  1971. public void addToolPack(UDFFinder toopack){
  1972. _udfFinder.add(toopack);
  1973. }
  1974. /**
  1975. * Whether the application shall perform a full recalculation when the workbook is opened.
  1976. * <p>
  1977. * Typically you want to force formula recalculation when you modify cell formulas or values
  1978. * of a workbook previously created by Excel. When set to true, this flag will tell Excel
  1979. * that it needs to recalculate all formulas in the workbook the next time the file is opened.
  1980. * </p>
  1981. * <p>
  1982. * Note, that recalculation updates cached formula results and, thus, modifies the workbook.
  1983. * Depending on the version, Excel may prompt you with "Do you want to save the changes in <em>filename</em>?"
  1984. * on close.
  1985. * </p>
  1986. *
  1987. * @param value true if the application will perform a full recalculation of
  1988. * workbook values when the workbook is opened
  1989. * @since 3.8
  1990. */
  1991. @Override
  1992. public void setForceFormulaRecalculation(boolean value){
  1993. CTWorkbook ctWorkbook = getCTWorkbook();
  1994. CTCalcPr calcPr = ctWorkbook.isSetCalcPr() ? ctWorkbook.getCalcPr() : ctWorkbook.addNewCalcPr();
  1995. // when set to true, will tell Excel that it needs to recalculate all formulas
  1996. // in the workbook the next time the file is opened.
  1997. calcPr.setFullCalcOnLoad(value);
  1998. if(value && calcPr.getCalcMode() == STCalcMode.MANUAL) {
  1999. calcPr.setCalcMode(STCalcMode.AUTO);
  2000. }
  2001. }
  2002. /**
  2003. * Whether Excel will be asked to recalculate all formulas when the workbook is opened.
  2004. *
  2005. * @since 3.8
  2006. */
  2007. @Override
  2008. public boolean getForceFormulaRecalculation(){
  2009. CTWorkbook ctWorkbook = getCTWorkbook();
  2010. CTCalcPr calcPr = ctWorkbook.getCalcPr();
  2011. return calcPr != null && calcPr.isSetFullCalcOnLoad() && calcPr.getFullCalcOnLoad();
  2012. }
  2013. /**
  2014. * Add pivotCache to the workbook
  2015. */
  2016. @Beta
  2017. protected CTPivotCache addPivotCache(String rId) {
  2018. CTWorkbook ctWorkbook = getCTWorkbook();
  2019. CTPivotCaches caches;
  2020. if (ctWorkbook.isSetPivotCaches()) {
  2021. caches = ctWorkbook.getPivotCaches();
  2022. } else {
  2023. caches = ctWorkbook.addNewPivotCaches();
  2024. }
  2025. CTPivotCache cache = caches.addNewPivotCache();
  2026. int tableId = getPivotTables().size()+1;
  2027. cache.setCacheId(tableId);
  2028. cache.setId(rId);
  2029. if(pivotCaches == null) {
  2030. pivotCaches = new ArrayList<>();
  2031. }
  2032. pivotCaches.add(cache);
  2033. return cache;
  2034. }
  2035. @Beta
  2036. public List<XSSFPivotTable> getPivotTables() {
  2037. return pivotTables;
  2038. }
  2039. @Beta
  2040. protected void setPivotTables(List<XSSFPivotTable> pivotTables) {
  2041. this.pivotTables = pivotTables;
  2042. }
  2043. public XSSFWorkbookType getWorkbookType() {
  2044. return isMacroEnabled() ? XSSFWorkbookType.XLSM : XSSFWorkbookType.XLSX;
  2045. }
  2046. /**
  2047. * Sets whether the workbook will be an .xlsx or .xlsm (macro-enabled) file.
  2048. */
  2049. public void setWorkbookType(XSSFWorkbookType type) {
  2050. try {
  2051. getPackagePart().setContentType(type.getContentType());
  2052. } catch (InvalidFormatException e) {
  2053. throw new POIXMLException(e);
  2054. }
  2055. }
  2056. /**
  2057. * Adds a vbaProject.bin file to the workbook. This will change the workbook
  2058. * type if necessary.
  2059. *
  2060. * @throws IOException If copying data from the stream fails.
  2061. */
  2062. public void setVBAProject(InputStream vbaProjectStream) throws IOException {
  2063. if (!isMacroEnabled()) {
  2064. setWorkbookType(XSSFWorkbookType.XLSM);
  2065. }
  2066. PackagePartName ppName;
  2067. try {
  2068. ppName = PackagingURIHelper.createPartName(XSSFRelation.VBA_MACROS.getDefaultFileName());
  2069. } catch (InvalidFormatException e) {
  2070. throw new POIXMLException(e);
  2071. }
  2072. OPCPackage opc = getPackage();
  2073. OutputStream outputStream;
  2074. if (!opc.containPart(ppName)) {
  2075. POIXMLDocumentPart relationship = createRelationship(XSSFRelation.VBA_MACROS, this.xssfFactory);
  2076. outputStream = relationship.getPackagePart().getOutputStream();
  2077. } else {
  2078. PackagePart part = opc.getPart(ppName);
  2079. outputStream = part.getOutputStream();
  2080. }
  2081. try {
  2082. IOUtils.copy(vbaProjectStream, outputStream);
  2083. } finally {
  2084. IOUtils.closeQuietly(outputStream);
  2085. }
  2086. }
  2087. /**
  2088. * Adds a vbaProject.bin file taken from another, given workbook to this one.
  2089. * @throws IOException If copying the VBAProject stream fails.
  2090. * @throws InvalidFormatException If an error occurs while handling parts of the XSSF format
  2091. */
  2092. public void setVBAProject(XSSFWorkbook macroWorkbook) throws IOException, InvalidFormatException {
  2093. if (!macroWorkbook.isMacroEnabled()) {
  2094. return;
  2095. }
  2096. InputStream vbaProjectStream = XSSFRelation.VBA_MACROS.getContents(macroWorkbook.getCorePart());
  2097. if (vbaProjectStream != null) {
  2098. setVBAProject(vbaProjectStream);
  2099. }
  2100. }
  2101. /**
  2102. * Returns the spreadsheet version (EXCLE2007) of this workbook
  2103. *
  2104. * @return EXCEL2007 SpreadsheetVersion enum
  2105. * @since 3.14 beta 2
  2106. */
  2107. @Override
  2108. public SpreadsheetVersion getSpreadsheetVersion() {
  2109. return SpreadsheetVersion.EXCEL2007;
  2110. }
  2111. /**
  2112. * Returns the data table with the given name (case insensitive).
  2113. *
  2114. * @param name the data table name (case-insensitive)
  2115. * @return The Data table in the workbook named <tt>name</tt>, or <tt>null</tt> if no table is named <tt>name</tt>.
  2116. * @since 3.15 beta 2
  2117. */
  2118. public XSSFTable getTable(String name) {
  2119. if (name != null && sheets != null) {
  2120. for (XSSFSheet sheet : sheets) {
  2121. for (XSSFTable tbl : sheet.getTables()) {
  2122. if (name.equalsIgnoreCase(tbl.getName())) {
  2123. return tbl;
  2124. }
  2125. }
  2126. }
  2127. }
  2128. return null;
  2129. }
  2130. @Override
  2131. public int addOlePackage(byte[] oleData, String label, String fileName, String command)
  2132. throws IOException {
  2133. // find an unused part name
  2134. OPCPackage opc = getPackage();
  2135. PackagePartName pnOLE;
  2136. int oleId=0;
  2137. do {
  2138. try {
  2139. pnOLE = PackagingURIHelper.createPartName( "/xl/embeddings/oleObject"+(++oleId)+".bin" );
  2140. } catch (InvalidFormatException e) {
  2141. throw new IOException("ole object name not recognized", e);
  2142. }
  2143. } while (opc.containPart(pnOLE));
  2144. PackagePart pp = opc.createPart( pnOLE, "application/vnd.openxmlformats-officedocument.oleObject" );
  2145. Ole10Native ole10 = new Ole10Native(label, fileName, command, oleData);
  2146. try (ByteArrayOutputStream bos = new ByteArrayOutputStream(oleData.length+500)) {
  2147. ole10.writeOut(bos);
  2148. try (POIFSFileSystem poifs = new POIFSFileSystem()) {
  2149. DirectoryNode root = poifs.getRoot();
  2150. root.createDocument(Ole10Native.OLE10_NATIVE, new ByteArrayInputStream(bos.toByteArray()));
  2151. root.setStorageClsid(ClassIDPredefined.OLE_V1_PACKAGE.getClassID());
  2152. // TODO: generate CombObj stream
  2153. try (OutputStream os = pp.getOutputStream()) {
  2154. poifs.writeFilesystem(os);
  2155. }
  2156. }
  2157. }
  2158. return oleId;
  2159. }
  2160. /**
  2161. * Whether a call to {@link XSSFCell#setCellFormula(String)} will validate the formula or not.
  2162. *
  2163. * @param value true if the application will validate the formula is correct
  2164. * @since 3.17
  2165. */
  2166. public void setCellFormulaValidation(final boolean value) {
  2167. this.cellFormulaValidation = value;
  2168. }
  2169. /**
  2170. * Whether a call to {@link XSSFCell#setCellFormula(String)} will validate the formula or not.
  2171. *
  2172. * @since 3.17
  2173. */
  2174. public boolean getCellFormulaValidation() {
  2175. return this.cellFormulaValidation;
  2176. }
  2177. }