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

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