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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678
  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 java.io.ByteArrayInputStream;
  17. import java.io.ByteArrayOutputStream;
  18. import java.io.File;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.OutputStream;
  22. import java.util.*;
  23. import java.util.regex.Pattern;
  24. import javax.xml.namespace.QName;
  25. import org.apache.poi.POIXMLDocument;
  26. import org.apache.poi.POIXMLDocumentPart;
  27. import org.apache.poi.POIXMLException;
  28. import org.apache.poi.POIXMLProperties;
  29. import org.apache.poi.ss.formula.SheetNameFormatter;
  30. import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
  31. import org.apache.poi.openxml4j.opc.OPCPackage;
  32. import org.apache.poi.openxml4j.opc.PackagePart;
  33. import org.apache.poi.openxml4j.opc.PackagePartName;
  34. import org.apache.poi.openxml4j.opc.PackageRelationship;
  35. import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
  36. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  37. import org.apache.poi.openxml4j.opc.TargetMode;
  38. import org.apache.poi.ss.formula.udf.UDFFinder;
  39. import org.apache.poi.ss.usermodel.Row;
  40. import org.apache.poi.ss.usermodel.Sheet;
  41. import org.apache.poi.ss.usermodel.Workbook;
  42. import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
  43. import org.apache.poi.ss.util.CellRangeAddress;
  44. import org.apache.poi.ss.util.CellReference;
  45. import org.apache.poi.ss.util.WorkbookUtil;
  46. import org.apache.poi.util.*;
  47. import org.apache.poi.xslf.usermodel.XSLFPictureData;
  48. import org.apache.poi.xssf.model.*;
  49. import org.apache.poi.xssf.usermodel.helpers.XSSFFormulaUtils;
  50. import org.apache.xmlbeans.XmlException;
  51. import org.apache.xmlbeans.XmlObject;
  52. import org.apache.xmlbeans.XmlOptions;
  53. import org.openxmlformats.schemas.officeDocument.x2006.relationships.STRelationshipId;
  54. import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
  55. /**
  56. * High level representation of a SpreadsheetML workbook. This is the first object most users
  57. * will construct whether they are reading or writing a workbook. It is also the
  58. * top level object for creating new sheets/etc.
  59. */
  60. public class XSSFWorkbook extends POIXMLDocument implements Workbook, Iterable<XSSFSheet> {
  61. private static final Pattern COMMA_PATTERN = Pattern.compile(",");
  62. /**
  63. * Width of one character of the default font in pixels. Same for Calibry and Arial.
  64. */
  65. public static final float DEFAULT_CHARACTER_WIDTH = 7.0017f;
  66. /**
  67. * Excel silently truncates long sheet names to 31 chars.
  68. * This constant is used to ensure uniqueness in the first 31 chars
  69. */
  70. private static final int MAX_SENSITIVE_SHEET_NAME_LEN = 31;
  71. /**
  72. * Images formats supported by XSSF but not by HSSF
  73. */
  74. public static final int PICTURE_TYPE_GIF = 8;
  75. public static final int PICTURE_TYPE_TIFF = 9;
  76. public static final int PICTURE_TYPE_EPS = 10;
  77. public static final int PICTURE_TYPE_BMP = 11;
  78. public static final int PICTURE_TYPE_WPG = 12;
  79. /**
  80. * The underlying XML bean
  81. */
  82. private CTWorkbook workbook;
  83. /**
  84. * this holds the XSSFSheet objects attached to this workbook
  85. */
  86. private List<XSSFSheet> sheets;
  87. /**
  88. * this holds the XSSFName objects attached to this workbook
  89. */
  90. private List<XSSFName> namedRanges;
  91. /**
  92. * shared string table - a cache of strings in this workbook
  93. */
  94. private SharedStringsTable sharedStringSource;
  95. /**
  96. * A collection of shared objects used for styling content,
  97. * e.g. fonts, cell styles, colors, etc.
  98. */
  99. private StylesTable stylesSource;
  100. private ThemesTable theme;
  101. /**
  102. * The locator of user-defined functions.
  103. * By default includes functions from the Excel Analysis Toolpack
  104. */
  105. private IndexedUDFFinder _udfFinder = new IndexedUDFFinder(UDFFinder.DEFAULT);
  106. /**
  107. * TODO
  108. */
  109. private CalculationChain calcChain;
  110. /**
  111. * A collection of custom XML mappings
  112. */
  113. private MapInfo mapInfo;
  114. /**
  115. * Used to keep track of the data formatter so that all
  116. * createDataFormatter calls return the same one for a given
  117. * book. This ensures that updates from one places is visible
  118. * someplace else.
  119. */
  120. private XSSFDataFormat formatter;
  121. /**
  122. * The policy to apply in the event of missing or
  123. * blank cells when fetching from a row.
  124. * See {@link org.apache.poi.ss.usermodel.Row.MissingCellPolicy}
  125. */
  126. private MissingCellPolicy _missingCellPolicy = Row.RETURN_NULL_AND_BLANK;
  127. /**
  128. * array of pictures for this workbook
  129. */
  130. private List<XSSFPictureData> pictures;
  131. private static POILogger logger = POILogFactory.getLogger(XSSFWorkbook.class);
  132. /**
  133. * cached instance of XSSFCreationHelper for this workbook
  134. * @see {@link #getCreationHelper()}
  135. */
  136. private XSSFCreationHelper _creationHelper;
  137. /**
  138. * Create a new SpreadsheetML workbook.
  139. */
  140. public XSSFWorkbook() {
  141. super(newPackage());
  142. onWorkbookCreate();
  143. }
  144. /**
  145. * Constructs a XSSFWorkbook object given a OpenXML4J <code>Package</code> object,
  146. * see <a href="http://poi.apache.org/oxml4j/">http://poi.apache.org/oxml4j/</a>.
  147. *
  148. * Once you have finished working with the Workbook, you should close the package
  149. * by calling pkg.close, to avoid leaving file handles open.
  150. *
  151. * Creating a XSSFWorkbook from a file-backed OPC Package has a lower memory
  152. * footprint than an InputStream backed one.
  153. *
  154. * @param pkg the OpenXML4J <code>OPC Package</code> object.
  155. */
  156. public XSSFWorkbook(OPCPackage pkg) throws IOException {
  157. super(pkg);
  158. //build a tree of POIXMLDocumentParts, this workbook being the root
  159. load(XSSFFactory.getInstance());
  160. }
  161. /**
  162. * Constructs a XSSFWorkbook object, by buffering the whole stream into memory
  163. * and then opening an {@link OPCPackage} object for it.
  164. *
  165. * Using an {@link InputStream} requires more memory than using a File, so
  166. * if a {@link File} is available then you should instead do something like
  167. * <pre><code>
  168. * OPCPackage pkg = OPCPackage.open(path);
  169. * XSSFWorkbook wb = new XSSFWorkbook(pkg);
  170. * // work with the wb object
  171. * ......
  172. * pkg.close(); // gracefully closes the underlying zip file
  173. * </code></pre>
  174. */
  175. public XSSFWorkbook(InputStream is) throws IOException {
  176. super(PackageHelper.open(is));
  177. //build a tree of POIXMLDocumentParts, this workbook being the root
  178. load(XSSFFactory.getInstance());
  179. }
  180. /**
  181. * Constructs a XSSFWorkbook object given a file name.
  182. *
  183. * <p>
  184. * This constructor is deprecated since POI-3.8 because it does not close
  185. * the underlying .zip file stream. In short, there are two ways to open a OPC package:
  186. * </p>
  187. * <ol>
  188. * <li>
  189. * from file which leads to invoking java.util.zip.ZipFile(File file)
  190. * deep in POI internals.
  191. * </li>
  192. * <li>
  193. * from input stream in which case we first read everything into memory and
  194. * then pass the data to ZipInputStream.
  195. * </li>
  196. * <ol>
  197. * <p>
  198. * It should be noted, that (2) uses quite a bit more memory than (1), which
  199. * doesn't need to hold the whole zip file in memory, and can take advantage
  200. * of native methods.
  201. * </p>
  202. * <p>
  203. * To construct a workbook from file use the
  204. * {@link #XSSFWorkbook(org.apache.poi.openxml4j.opc.OPCPackage)} constructor:
  205. * <pre><code>
  206. * OPCPackage pkg = OPCPackage.open(path);
  207. * XSSFWorkbook wb = new XSSFWorkbook(pkg);
  208. * // work with the wb object
  209. * ......
  210. * pkg.close(); // gracefully closes the underlying zip file
  211. * </code></pre>
  212. * </p>
  213. *
  214. * @param path the file name.
  215. * @deprecated
  216. */
  217. @Deprecated
  218. public XSSFWorkbook(String path) throws IOException {
  219. this(openPackage(path));
  220. }
  221. @Override
  222. @SuppressWarnings("deprecation") // getXYZArray() array accessors are deprecated
  223. protected void onDocumentRead() throws IOException {
  224. try {
  225. WorkbookDocument doc = WorkbookDocument.Factory.parse(getPackagePart().getInputStream());
  226. this.workbook = doc.getWorkbook();
  227. Map<String, XSSFSheet> shIdMap = new HashMap<String, XSSFSheet>();
  228. for(POIXMLDocumentPart p : getRelations()){
  229. if(p instanceof SharedStringsTable) sharedStringSource = (SharedStringsTable)p;
  230. else if(p instanceof StylesTable) stylesSource = (StylesTable)p;
  231. else if(p instanceof ThemesTable) theme = (ThemesTable)p;
  232. else if(p instanceof CalculationChain) calcChain = (CalculationChain)p;
  233. else if(p instanceof MapInfo) mapInfo = (MapInfo)p;
  234. else if (p instanceof XSSFSheet) {
  235. shIdMap.put(p.getPackageRelationship().getId(), (XSSFSheet)p);
  236. }
  237. }
  238. stylesSource.setTheme(theme);
  239. if(sharedStringSource == null) {
  240. //Create SST if it is missing
  241. sharedStringSource = (SharedStringsTable)createRelationship(XSSFRelation.SHARED_STRINGS, XSSFFactory.getInstance());
  242. }
  243. // Load individual sheets. The order of sheets is defined by the order of CTSheet elements in the workbook
  244. sheets = new ArrayList<XSSFSheet>(shIdMap.size());
  245. for (CTSheet ctSheet : this.workbook.getSheets().getSheetArray()) {
  246. XSSFSheet sh = shIdMap.get(ctSheet.getId());
  247. if(sh == null) {
  248. logger.log(POILogger.WARN, "Sheet with name " + ctSheet.getName() + " and r:id " + ctSheet.getId()+ " was defined, but didn't exist in package, skipping");
  249. continue;
  250. }
  251. sh.sheet = ctSheet;
  252. sh.onDocumentRead();
  253. sheets.add(sh);
  254. }
  255. // Process the named ranges
  256. namedRanges = new ArrayList<XSSFName>();
  257. if(workbook.isSetDefinedNames()) {
  258. for(CTDefinedName ctName : workbook.getDefinedNames().getDefinedNameArray()) {
  259. namedRanges.add(new XSSFName(ctName, this));
  260. }
  261. }
  262. } catch (XmlException e) {
  263. throw new POIXMLException(e);
  264. }
  265. }
  266. /**
  267. * Create a new CTWorkbook with all values set to default
  268. */
  269. private void onWorkbookCreate() {
  270. workbook = CTWorkbook.Factory.newInstance();
  271. // don't EVER use the 1904 date system
  272. CTWorkbookPr workbookPr = workbook.addNewWorkbookPr();
  273. workbookPr.setDate1904(false);
  274. CTBookViews bvs = workbook.addNewBookViews();
  275. CTBookView bv = bvs.addNewWorkbookView();
  276. bv.setActiveTab(0);
  277. workbook.addNewSheets();
  278. POIXMLProperties.ExtendedProperties expProps = getProperties().getExtendedProperties();
  279. expProps.getUnderlyingProperties().setApplication(DOCUMENT_CREATOR);
  280. sharedStringSource = (SharedStringsTable)createRelationship(XSSFRelation.SHARED_STRINGS, XSSFFactory.getInstance());
  281. stylesSource = (StylesTable)createRelationship(XSSFRelation.STYLES, XSSFFactory.getInstance());
  282. namedRanges = new ArrayList<XSSFName>();
  283. sheets = new ArrayList<XSSFSheet>();
  284. }
  285. /**
  286. * Create a new SpreadsheetML package and setup the default minimal content
  287. */
  288. protected static OPCPackage newPackage() {
  289. try {
  290. OPCPackage pkg = OPCPackage.create(new ByteArrayOutputStream());
  291. // Main part
  292. PackagePartName corePartName = PackagingURIHelper.createPartName(XSSFRelation.WORKBOOK.getDefaultFileName());
  293. // Create main part relationship
  294. pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT);
  295. // Create main document part
  296. pkg.createPart(corePartName, XSSFRelation.WORKBOOK.getContentType());
  297. pkg.getPackageProperties().setCreatorProperty(DOCUMENT_CREATOR);
  298. return pkg;
  299. } catch (Exception e){
  300. throw new POIXMLException(e);
  301. }
  302. }
  303. /**
  304. * Return the underlying XML bean
  305. *
  306. * @return the underlying CTWorkbook bean
  307. */
  308. @Internal
  309. public CTWorkbook getCTWorkbook() {
  310. return this.workbook;
  311. }
  312. /**
  313. * Adds a picture to the workbook.
  314. *
  315. * @param pictureData The bytes of the picture
  316. * @param format The format of the picture.
  317. *
  318. * @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} .
  319. * @see Workbook#PICTURE_TYPE_EMF
  320. * @see Workbook#PICTURE_TYPE_WMF
  321. * @see Workbook#PICTURE_TYPE_PICT
  322. * @see Workbook#PICTURE_TYPE_JPEG
  323. * @see Workbook#PICTURE_TYPE_PNG
  324. * @see Workbook#PICTURE_TYPE_DIB
  325. * @see #getAllPictures()
  326. */
  327. public int addPicture(byte[] pictureData, int format) {
  328. int imageNumber = getAllPictures().size() + 1;
  329. XSSFPictureData img = (XSSFPictureData)createRelationship(XSSFPictureData.RELATIONS[format], XSSFFactory.getInstance(), imageNumber, true);
  330. try {
  331. OutputStream out = img.getPackagePart().getOutputStream();
  332. out.write(pictureData);
  333. out.close();
  334. } catch (IOException e){
  335. throw new POIXMLException(e);
  336. }
  337. pictures.add(img);
  338. return imageNumber - 1;
  339. }
  340. /**
  341. * Adds a picture to the workbook.
  342. *
  343. * @param is The sream to read image from
  344. * @param format The format of the picture.
  345. *
  346. * @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} .
  347. * @see Workbook#PICTURE_TYPE_EMF
  348. * @see Workbook#PICTURE_TYPE_WMF
  349. * @see Workbook#PICTURE_TYPE_PICT
  350. * @see Workbook#PICTURE_TYPE_JPEG
  351. * @see Workbook#PICTURE_TYPE_PNG
  352. * @see Workbook#PICTURE_TYPE_DIB
  353. * @see #getAllPictures()
  354. */
  355. public int addPicture(InputStream is, int format) throws IOException {
  356. int imageNumber = getAllPictures().size() + 1;
  357. XSSFPictureData img = (XSSFPictureData)createRelationship(XSSFPictureData.RELATIONS[format], XSSFFactory.getInstance(), imageNumber, true);
  358. OutputStream out = img.getPackagePart().getOutputStream();
  359. IOUtils.copy(is, out);
  360. out.close();
  361. pictures.add(img);
  362. return imageNumber - 1;
  363. }
  364. /**
  365. * Create an XSSFSheet from an existing sheet in the XSSFWorkbook.
  366. * The cloned sheet is a deep copy of the original.
  367. *
  368. * @return XSSFSheet representing the cloned sheet.
  369. * @throws IllegalArgumentException if the sheet index in invalid
  370. * @throws POIXMLException if there were errors when cloning
  371. */
  372. public XSSFSheet cloneSheet(int sheetNum) {
  373. validateSheetIndex(sheetNum);
  374. XSSFSheet srcSheet = sheets.get(sheetNum);
  375. String srcName = srcSheet.getSheetName();
  376. String clonedName = getUniqueSheetName(srcName);
  377. XSSFSheet clonedSheet = createSheet(clonedName);
  378. try {
  379. ByteArrayOutputStream out = new ByteArrayOutputStream();
  380. srcSheet.write(out);
  381. clonedSheet.read(new ByteArrayInputStream(out.toByteArray()));
  382. } catch (IOException e){
  383. throw new POIXMLException("Failed to clone sheet", e);
  384. }
  385. CTWorksheet ct = clonedSheet.getCTWorksheet();
  386. if(ct.isSetLegacyDrawing()) {
  387. logger.log(POILogger.WARN, "Cloning sheets with comments is not yet supported.");
  388. ct.unsetLegacyDrawing();
  389. }
  390. if (ct.isSetPageSetup()) {
  391. logger.log(POILogger.WARN, "Cloning sheets with page setup is not yet supported.");
  392. ct.unsetPageSetup();
  393. }
  394. clonedSheet.setSelected(false);
  395. // copy sheet's relations
  396. List<POIXMLDocumentPart> rels = srcSheet.getRelations();
  397. // if the sheet being cloned has a drawing then rememebr it and re-create tpoo
  398. XSSFDrawing dg = null;
  399. for(POIXMLDocumentPart r : rels) {
  400. // do not copy the drawing relationship, it will be re-created
  401. if(r instanceof XSSFDrawing) {
  402. dg = (XSSFDrawing)r;
  403. continue;
  404. }
  405. PackageRelationship rel = r.getPackageRelationship();
  406. clonedSheet.getPackagePart().addRelationship(
  407. rel.getTargetURI(), rel.getTargetMode(),rel.getRelationshipType());
  408. clonedSheet.addRelation(rel.getId(), r);
  409. }
  410. // clone the sheet drawing alongs with its relationships
  411. if (dg != null) {
  412. if(ct.isSetDrawing()) {
  413. // unset the existing reference to the drawing,
  414. // so that subsequent call of clonedSheet.createDrawingPatriarch() will create a new one
  415. ct.unsetDrawing();
  416. }
  417. XSSFDrawing clonedDg = clonedSheet.createDrawingPatriarch();
  418. // copy drawing contents
  419. clonedDg.getCTDrawing().set(dg.getCTDrawing());
  420. // Clone drawing relations
  421. List<POIXMLDocumentPart> srcRels = srcSheet.createDrawingPatriarch().getRelations();
  422. for (POIXMLDocumentPart rel : srcRels) {
  423. PackageRelationship relation = rel.getPackageRelationship();
  424. clonedSheet
  425. .createDrawingPatriarch()
  426. .getPackagePart()
  427. .addRelationship(relation.getTargetURI(), relation.getTargetMode(),
  428. relation.getRelationshipType(), relation.getId());
  429. }
  430. }
  431. return clonedSheet;
  432. }
  433. /**
  434. * Generate a valid sheet name based on the existing one. Used when cloning sheets.
  435. *
  436. * @param srcName the original sheet name to
  437. * @return clone sheet name
  438. */
  439. private String getUniqueSheetName(String srcName) {
  440. int uniqueIndex = 2;
  441. String baseName = srcName;
  442. int bracketPos = srcName.lastIndexOf('(');
  443. if (bracketPos > 0 && srcName.endsWith(")")) {
  444. String suffix = srcName.substring(bracketPos + 1, srcName.length() - ")".length());
  445. try {
  446. uniqueIndex = Integer.parseInt(suffix.trim());
  447. uniqueIndex++;
  448. baseName = srcName.substring(0, bracketPos).trim();
  449. } catch (NumberFormatException e) {
  450. // contents of brackets not numeric
  451. }
  452. }
  453. while (true) {
  454. // Try and find the next sheet name that is unique
  455. String index = Integer.toString(uniqueIndex++);
  456. String name;
  457. if (baseName.length() + index.length() + 2 < 31) {
  458. name = baseName + " (" + index + ")";
  459. } else {
  460. name = baseName.substring(0, 31 - index.length() - 2) + "(" + index + ")";
  461. }
  462. //If the sheet name is unique, then set it otherwise move on to the next number.
  463. if (getSheetIndex(name) == -1) {
  464. return name;
  465. }
  466. }
  467. }
  468. /**
  469. * Create a new XSSFCellStyle and add it to the workbook's style table
  470. *
  471. * @return the new XSSFCellStyle object
  472. */
  473. public XSSFCellStyle createCellStyle() {
  474. return stylesSource.createCellStyle();
  475. }
  476. /**
  477. * Returns the instance of XSSFDataFormat for this workbook.
  478. *
  479. * @return the XSSFDataFormat object
  480. * @see org.apache.poi.ss.usermodel.DataFormat
  481. */
  482. public XSSFDataFormat createDataFormat() {
  483. if (formatter == null)
  484. formatter = new XSSFDataFormat(stylesSource);
  485. return formatter;
  486. }
  487. /**
  488. * Create a new Font and add it to the workbook's font table
  489. *
  490. * @return new font object
  491. */
  492. public XSSFFont createFont() {
  493. XSSFFont font = new XSSFFont();
  494. font.registerTo(stylesSource);
  495. return font;
  496. }
  497. public XSSFName createName() {
  498. CTDefinedName ctName = CTDefinedName.Factory.newInstance();
  499. ctName.setName("");
  500. XSSFName name = new XSSFName(ctName, this);
  501. namedRanges.add(name);
  502. return name;
  503. }
  504. /**
  505. * Create an XSSFSheet for this workbook, adds it to the sheets and returns
  506. * the high level representation. Use this to create new sheets.
  507. *
  508. * @return XSSFSheet representing the new sheet.
  509. */
  510. public XSSFSheet createSheet() {
  511. String sheetname = "Sheet" + (sheets.size());
  512. int idx = 0;
  513. while(getSheet(sheetname) != null) {
  514. sheetname = "Sheet" + idx;
  515. idx++;
  516. }
  517. return createSheet(sheetname);
  518. }
  519. /**
  520. * Create a new sheet for this Workbook and return the high level representation.
  521. * Use this to create new sheets.
  522. *
  523. * <p>
  524. * Note that Excel allows sheet names up to 31 chars in length but other applications
  525. * (such as OpenOffice) allow more. Some versions of Excel crash with names longer than 31 chars,
  526. * others - truncate such names to 31 character.
  527. * </p>
  528. * <p>
  529. * POI's SpreadsheetAPI silently truncates the input argument to 31 characters.
  530. * Example:
  531. *
  532. * <pre><code>
  533. * Sheet sheet = workbook.createSheet("My very long sheet name which is longer than 31 chars"); // will be truncated
  534. * assert 31 == sheet.getSheetName().length();
  535. * assert "My very long sheet name which i" == sheet.getSheetName();
  536. * </code></pre>
  537. * </p>
  538. *
  539. * Except the 31-character constraint, Excel applies some other rules:
  540. * <p>
  541. * Sheet name MUST be unique in the workbook and MUST NOT contain the any of the following characters:
  542. * <ul>
  543. * <li> 0x0000 </li>
  544. * <li> 0x0003 </li>
  545. * <li> colon (:) </li>
  546. * <li> backslash (\) </li>
  547. * <li> asterisk (*) </li>
  548. * <li> question mark (?) </li>
  549. * <li> forward slash (/) </li>
  550. * <li> opening square bracket ([) </li>
  551. * <li> closing square bracket (]) </li>
  552. * </ul>
  553. * The string MUST NOT begin or end with the single quote (') character.
  554. * </p>
  555. *
  556. * <p>
  557. * See {@link org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)}
  558. * for a safe way to create valid names
  559. * </p>
  560. * @param sheetname sheetname to set for the sheet.
  561. * @return Sheet representing the new sheet.
  562. * @throws IllegalArgumentException if the name is null or invalid
  563. * or workbook already contains a sheet with this name
  564. * @see org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)
  565. */
  566. public XSSFSheet createSheet(String sheetname) {
  567. if (sheetname == null) {
  568. throw new IllegalArgumentException("sheetName must not be null");
  569. }
  570. if (containsSheet( sheetname, sheets.size() ))
  571. throw new IllegalArgumentException( "The workbook already contains a sheet of this name");
  572. // YK: Mimic Excel and silently truncate sheet names longer than 31 characters
  573. if(sheetname.length() > 31) sheetname = sheetname.substring(0, 31);
  574. WorkbookUtil.validateSheetName(sheetname);
  575. CTSheet sheet = addSheet(sheetname);
  576. int sheetNumber = 1;
  577. for(XSSFSheet sh : sheets) sheetNumber = (int)Math.max(sh.sheet.getSheetId() + 1, sheetNumber);
  578. XSSFSheet wrapper = (XSSFSheet)createRelationship(XSSFRelation.WORKSHEET, XSSFFactory.getInstance(), sheetNumber);
  579. wrapper.sheet = sheet;
  580. sheet.setId(wrapper.getPackageRelationship().getId());
  581. sheet.setSheetId(sheetNumber);
  582. if(sheets.size() == 0) wrapper.setSelected(true);
  583. sheets.add(wrapper);
  584. return wrapper;
  585. }
  586. protected XSSFDialogsheet createDialogsheet(String sheetname, CTDialogsheet dialogsheet) {
  587. XSSFSheet sheet = createSheet(sheetname);
  588. return new XSSFDialogsheet(sheet);
  589. }
  590. private CTSheet addSheet(String sheetname) {
  591. CTSheet sheet = workbook.getSheets().addNewSheet();
  592. sheet.setName(sheetname);
  593. return sheet;
  594. }
  595. /**
  596. * Finds a font that matches the one with the supplied attributes
  597. */
  598. public XSSFFont findFont(short boldWeight, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) {
  599. return stylesSource.findFont(boldWeight, color, fontHeight, name, italic, strikeout, typeOffset, underline);
  600. }
  601. /**
  602. * Convenience method to get the active sheet. The active sheet is is the sheet
  603. * which is currently displayed when the workbook is viewed in Excel.
  604. * 'Selected' sheet(s) is a distinct concept.
  605. */
  606. public int getActiveSheetIndex() {
  607. //activeTab (Active Sheet Index) Specifies an unsignedInt
  608. //that contains the index to the active sheet in this book view.
  609. return (int)workbook.getBookViews().getWorkbookViewArray(0).getActiveTab();
  610. }
  611. /**
  612. * Gets all pictures from the Workbook.
  613. *
  614. * @return the list of pictures (a list of {@link XSSFPictureData} objects.)
  615. * @see #addPicture(byte[], int)
  616. */
  617. public List<XSSFPictureData> getAllPictures() {
  618. if(pictures == null){
  619. List<PackagePart> mediaParts = getPackage().getPartsByName(Pattern.compile("/xl/media/.*?"));
  620. pictures = new ArrayList<XSSFPictureData>(mediaParts.size());
  621. for(PackagePart part : mediaParts){
  622. pictures.add(new XSSFPictureData(part, null));
  623. }
  624. }
  625. return pictures; //YK: should return Collections.unmodifiableList(pictures);
  626. }
  627. /**
  628. * Get the cell style object at the given index
  629. *
  630. * @param idx index within the set of styles
  631. * @return XSSFCellStyle object at the index
  632. */
  633. public XSSFCellStyle getCellStyleAt(short idx) {
  634. return stylesSource.getStyleAt(idx);
  635. }
  636. /**
  637. * Get the font at the given index number
  638. *
  639. * @param idx index number
  640. * @return XSSFFont at the index
  641. */
  642. public XSSFFont getFontAt(short idx) {
  643. return stylesSource.getFontAt(idx);
  644. }
  645. public XSSFName getName(String name) {
  646. int nameIndex = getNameIndex(name);
  647. if (nameIndex < 0) {
  648. return null;
  649. }
  650. return namedRanges.get(nameIndex);
  651. }
  652. public XSSFName getNameAt(int nameIndex) {
  653. int nNames = namedRanges.size();
  654. if (nNames < 1) {
  655. throw new IllegalStateException("There are no defined names in this workbook");
  656. }
  657. if (nameIndex < 0 || nameIndex > nNames) {
  658. throw new IllegalArgumentException("Specified name index " + nameIndex
  659. + " is outside the allowable range (0.." + (nNames-1) + ").");
  660. }
  661. return namedRanges.get(nameIndex);
  662. }
  663. /**
  664. * Gets the named range index by his name
  665. * <i>Note:</i>Excel named ranges are case-insensitive and
  666. * this method performs a case-insensitive search.
  667. *
  668. * @param name named range name
  669. * @return named range index
  670. */
  671. public int getNameIndex(String name) {
  672. int i = 0;
  673. for(XSSFName nr : namedRanges) {
  674. if(nr.getNameName().equals(name)) {
  675. return i;
  676. }
  677. i++;
  678. }
  679. return -1;
  680. }
  681. /**
  682. * Get the number of styles the workbook contains
  683. *
  684. * @return count of cell styles
  685. */
  686. public short getNumCellStyles() {
  687. return (short) (stylesSource).getNumCellStyles();
  688. }
  689. /**
  690. * Get the number of fonts in the this workbook
  691. *
  692. * @return number of fonts
  693. */
  694. public short getNumberOfFonts() {
  695. return (short)stylesSource.getFonts().size();
  696. }
  697. /**
  698. * Get the number of named ranges in the this workbook
  699. *
  700. * @return number of named ranges
  701. */
  702. public int getNumberOfNames() {
  703. return namedRanges.size();
  704. }
  705. /**
  706. * Get the number of worksheets in the this workbook
  707. *
  708. * @return number of worksheets
  709. */
  710. public int getNumberOfSheets() {
  711. return sheets.size();
  712. }
  713. /**
  714. * Retrieves the reference for the printarea of the specified sheet, the sheet name is appended to the reference even if it was not specified.
  715. * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java)
  716. * @return String Null if no print area has been defined
  717. */
  718. public String getPrintArea(int sheetIndex) {
  719. XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
  720. if (name == null) return null;
  721. //adding one here because 0 indicates a global named region; doesnt make sense for print areas
  722. return name.getRefersToFormula();
  723. }
  724. /**
  725. * Get sheet with the given name (case insensitive match)
  726. *
  727. * @param name of the sheet
  728. * @return XSSFSheet with the name provided or <code>null</code> if it does not exist
  729. */
  730. public XSSFSheet getSheet(String name) {
  731. for (XSSFSheet sheet : sheets) {
  732. if (name.equalsIgnoreCase(sheet.getSheetName())) {
  733. return sheet;
  734. }
  735. }
  736. return null;
  737. }
  738. /**
  739. * Get the XSSFSheet object at the given index.
  740. *
  741. * @param index of the sheet number (0-based physical & logical)
  742. * @return XSSFSheet at the provided index
  743. * @throws IllegalArgumentException if the index is out of range (index
  744. * &lt; 0 || index &gt;= getNumberOfSheets()).
  745. */
  746. public XSSFSheet getSheetAt(int index) {
  747. validateSheetIndex(index);
  748. return sheets.get(index);
  749. }
  750. /**
  751. * Returns the index of the sheet by his name (case insensitive match)
  752. *
  753. * @param name the sheet name
  754. * @return index of the sheet (0 based) or <tt>-1</tt if not found
  755. */
  756. public int getSheetIndex(String name) {
  757. for (int i = 0 ; i < sheets.size() ; ++i) {
  758. XSSFSheet sheet = sheets.get(i);
  759. if (name.equalsIgnoreCase(sheet.getSheetName())) {
  760. return i;
  761. }
  762. }
  763. return -1;
  764. }
  765. /**
  766. * Returns the index of the given sheet
  767. *
  768. * @param sheet the sheet to look up
  769. * @return index of the sheet (0 based). <tt>-1</tt> if not found
  770. */
  771. public int getSheetIndex(Sheet sheet) {
  772. int idx = 0;
  773. for(XSSFSheet sh : sheets){
  774. if(sh == sheet) return idx;
  775. idx++;
  776. }
  777. return -1;
  778. }
  779. /**
  780. * Get the sheet name
  781. *
  782. * @param sheetIx Number
  783. * @return Sheet name
  784. */
  785. public String getSheetName(int sheetIx) {
  786. validateSheetIndex(sheetIx);
  787. return sheets.get(sheetIx).getSheetName();
  788. }
  789. /**
  790. * Allows foreach loops:
  791. * <pre><code>
  792. * XSSFWorkbook wb = new XSSFWorkbook(package);
  793. * for(XSSFSheet sheet : wb){
  794. *
  795. * }
  796. * </code></pre>
  797. */
  798. public Iterator<XSSFSheet> iterator() {
  799. return sheets.iterator();
  800. }
  801. /**
  802. * Are we a normal workbook (.xlsx), or a
  803. * macro enabled workbook (.xlsm)?
  804. */
  805. public boolean isMacroEnabled() {
  806. return getPackagePart().getContentType().equals(XSSFRelation.MACROS_WORKBOOK.getContentType());
  807. }
  808. public void removeName(int nameIndex) {
  809. namedRanges.remove(nameIndex);
  810. }
  811. public void removeName(String name) {
  812. for (int i = 0; i < namedRanges.size(); i++) {
  813. XSSFName nm = namedRanges.get(i);
  814. if(nm.getNameName().equalsIgnoreCase(name)) {
  815. removeName(i);
  816. return;
  817. }
  818. }
  819. throw new IllegalArgumentException("Named range was not found: " + name);
  820. }
  821. /**
  822. * As {@link #removeName(String)} is not necessarily unique
  823. * (name + sheet index is unique), this method is more accurate.
  824. *
  825. * @param name the name to remove.
  826. */
  827. void removeName(XSSFName name) {
  828. if (!namedRanges.remove(name)) {
  829. throw new IllegalArgumentException("Name was not found: " + name);
  830. }
  831. }
  832. /**
  833. * Delete the printarea for the sheet specified
  834. *
  835. * @param sheetIndex 0-based sheet index (0 = First Sheet)
  836. */
  837. public void removePrintArea(int sheetIndex) {
  838. int cont = 0;
  839. for (XSSFName name : namedRanges) {
  840. if (name.getNameName().equals(XSSFName.BUILTIN_PRINT_AREA) && name.getSheetIndex() == sheetIndex) {
  841. namedRanges.remove(cont);
  842. break;
  843. }
  844. cont++;
  845. }
  846. }
  847. /**
  848. * Removes sheet at the given index.<p/>
  849. *
  850. * Care must be taken if the removed sheet is the currently active or only selected sheet in
  851. * the workbook. There are a few situations when Excel must have a selection and/or active
  852. * sheet. (For example when printing - see Bug 40414).<br/>
  853. *
  854. * This method makes sure that if the removed sheet was active, another sheet will become
  855. * active in its place. Furthermore, if the removed sheet was the only selected sheet, another
  856. * sheet will become selected. The newly active/selected sheet will have the same index, or
  857. * one less if the removed sheet was the last in the workbook.
  858. *
  859. * @param index of the sheet (0-based)
  860. */
  861. public void removeSheetAt(int index) {
  862. validateSheetIndex(index);
  863. onSheetDelete(index);
  864. XSSFSheet sheet = getSheetAt(index);
  865. removeRelation(sheet);
  866. sheets.remove(index);
  867. }
  868. /**
  869. * Gracefully remove references to the sheet being deleted
  870. *
  871. * @param index the 0-based index of the sheet to delete
  872. */
  873. private void onSheetDelete(int index) {
  874. //delete the CTSheet reference from workbook.xml
  875. workbook.getSheets().removeSheet(index);
  876. //calculation chain is auxiliary, remove it as it may contain orphan references to deleted cells
  877. if(calcChain != null) {
  878. removeRelation(calcChain);
  879. calcChain = null;
  880. }
  881. //adjust indices of names ranges
  882. for (Iterator<XSSFName> it = namedRanges.iterator(); it.hasNext();) {
  883. XSSFName nm = it.next();
  884. CTDefinedName ct = nm.getCTName();
  885. if(!ct.isSetLocalSheetId()) continue;
  886. if (ct.getLocalSheetId() == index) {
  887. it.remove();
  888. } else if (ct.getLocalSheetId() > index){
  889. // Bump down by one, so still points at the same sheet
  890. ct.setLocalSheetId(ct.getLocalSheetId()-1);
  891. }
  892. }
  893. }
  894. /**
  895. * Retrieves the current policy on what to do when
  896. * getting missing or blank cells from a row.
  897. * The default is to return blank and null cells.
  898. * {@link MissingCellPolicy}
  899. */
  900. public MissingCellPolicy getMissingCellPolicy() {
  901. return _missingCellPolicy;
  902. }
  903. /**
  904. * Sets the policy on what to do when
  905. * getting missing or blank cells from a row.
  906. * This will then apply to all calls to
  907. * {@link Row#getCell(int)}}. See
  908. * {@link MissingCellPolicy}
  909. */
  910. public void setMissingCellPolicy(MissingCellPolicy missingCellPolicy) {
  911. _missingCellPolicy = missingCellPolicy;
  912. }
  913. /**
  914. * Convenience method to set the active sheet. The active sheet is is the sheet
  915. * which is currently displayed when the workbook is viewed in Excel.
  916. * 'Selected' sheet(s) is a distinct concept.
  917. */
  918. @SuppressWarnings("deprecation") //YK: getXYZArray() array accessors are deprecated in xmlbeans with JDK 1.5 support
  919. public void setActiveSheet(int index) {
  920. validateSheetIndex(index);
  921. for (CTBookView arrayBook : workbook.getBookViews().getWorkbookViewArray()) {
  922. arrayBook.setActiveTab(index);
  923. }
  924. }
  925. /**
  926. * Validate sheet index
  927. *
  928. * @param index the index to validate
  929. * @throws IllegalArgumentException if the index is out of range (index
  930. * &lt; 0 || index &gt;= getNumberOfSheets()).
  931. */
  932. private void validateSheetIndex(int index) {
  933. int lastSheetIx = sheets.size() - 1;
  934. if (index < 0 || index > lastSheetIx) {
  935. throw new IllegalArgumentException("Sheet index ("
  936. + index +") is out of range (0.." + lastSheetIx + ")");
  937. }
  938. }
  939. /**
  940. * Gets the first tab that is displayed in the list of tabs in excel.
  941. *
  942. * @return integer that contains the index to the active sheet in this book view.
  943. */
  944. public int getFirstVisibleTab() {
  945. CTBookViews bookViews = workbook.getBookViews();
  946. CTBookView bookView = bookViews.getWorkbookViewArray(0);
  947. return (short) bookView.getActiveTab();
  948. }
  949. /**
  950. * Sets the first tab that is displayed in the list of tabs in excel.
  951. *
  952. * @param index integer that contains the index to the active sheet in this book view.
  953. */
  954. public void setFirstVisibleTab(int index) {
  955. CTBookViews bookViews = workbook.getBookViews();
  956. CTBookView bookView= bookViews.getWorkbookViewArray(0);
  957. bookView.setActiveTab(index);
  958. }
  959. /**
  960. * Sets the printarea for the sheet provided
  961. * <p>
  962. * i.e. Reference = $A$1:$B$2
  963. * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java)
  964. * @param reference Valid name Reference for the Print Area
  965. */
  966. public void setPrintArea(int sheetIndex, String reference) {
  967. XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
  968. if (name == null) {
  969. name = createBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
  970. }
  971. //short externSheetIndex = getWorkbook().checkExternSheet(sheetIndex);
  972. //name.setExternSheetNumber(externSheetIndex);
  973. String[] parts = COMMA_PATTERN.split(reference);
  974. StringBuffer sb = new StringBuffer(32);
  975. for (int i = 0; i < parts.length; i++) {
  976. if(i>0) {
  977. sb.append(",");
  978. }
  979. SheetNameFormatter.appendFormat(sb, getSheetName(sheetIndex));
  980. sb.append("!");
  981. sb.append(parts[i]);
  982. }
  983. name.setRefersToFormula(sb.toString());
  984. }
  985. /**
  986. * For the Convenience of Java Programmers maintaining pointers.
  987. * @see #setPrintArea(int, String)
  988. * @param sheetIndex Zero-based sheet index (0 = First Sheet)
  989. * @param startColumn Column to begin printarea
  990. * @param endColumn Column to end the printarea
  991. * @param startRow Row to begin the printarea
  992. * @param endRow Row to end the printarea
  993. */
  994. public void setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow) {
  995. String reference=getReferencePrintArea(getSheetName(sheetIndex), startColumn, endColumn, startRow, endRow);
  996. setPrintArea(sheetIndex, reference);
  997. }
  998. /**
  999. * Sets the repeating rows and columns for a sheet.
  1000. * <p/>
  1001. * To set just repeating columns:
  1002. * <pre>
  1003. * workbook.setRepeatingRowsAndColumns(0,0,1,-1,-1);
  1004. * </pre>
  1005. * To set just repeating rows:
  1006. * <pre>
  1007. * workbook.setRepeatingRowsAndColumns(0,-1,-1,0,4);
  1008. * </pre>
  1009. * To remove all repeating rows and columns for a sheet.
  1010. * <pre>
  1011. * workbook.setRepeatingRowsAndColumns(0,-1,-1,-1,-1);
  1012. * </pre>
  1013. *
  1014. * @param sheetIndex 0 based index to sheet.
  1015. * @param startColumn 0 based start of repeating columns.
  1016. * @param endColumn 0 based end of repeating columns.
  1017. * @param startRow 0 based start of repeating rows.
  1018. * @param endRow 0 based end of repeating rows.
  1019. *
  1020. * @deprecated use {@link XSSFSheet#setRepeatingRows(CellRangeAddress)}
  1021. * or {@link XSSFSheet#setRepeatingColumns(CellRangeAddress)}
  1022. */
  1023. public void setRepeatingRowsAndColumns(int sheetIndex,
  1024. int startColumn, int endColumn,
  1025. int startRow, int endRow) {
  1026. XSSFSheet sheet = getSheetAt(sheetIndex);
  1027. CellRangeAddress rows = null;
  1028. CellRangeAddress cols = null;
  1029. if (startRow != -1) {
  1030. rows = new CellRangeAddress(startRow, endRow, -1, -1);
  1031. }
  1032. if (startColumn != -1) {
  1033. cols = new CellRangeAddress(-1, -1, startColumn, endColumn);
  1034. }
  1035. sheet.setRepeatingRows(rows);
  1036. sheet.setRepeatingColumns(cols);
  1037. }
  1038. private static String getReferencePrintArea(String sheetName, int startC, int endC, int startR, int endR) {
  1039. //windows excel example: Sheet1!$C$3:$E$4
  1040. CellReference colRef = new CellReference(sheetName, startR, startC, true, true);
  1041. CellReference colRef2 = new CellReference(sheetName, endR, endC, true, true);
  1042. return "$" + colRef.getCellRefParts()[2] + "$" + colRef.getCellRefParts()[1] + ":$" + colRef2.getCellRefParts()[2] + "$" + colRef2.getCellRefParts()[1];
  1043. }
  1044. XSSFName getBuiltInName(String builtInCode, int sheetNumber) {
  1045. for (XSSFName name : namedRanges) {
  1046. if (name.getNameName().equalsIgnoreCase(builtInCode) && name.getSheetIndex() == sheetNumber) {
  1047. return name;
  1048. }
  1049. }
  1050. return null;
  1051. }
  1052. /**
  1053. * Generates a NameRecord to represent a built-in region
  1054. *
  1055. * @return a new NameRecord
  1056. * @throws IllegalArgumentException if sheetNumber is invalid
  1057. * @throws POIXMLException if such a name already exists in the workbook
  1058. */
  1059. XSSFName createBuiltInName(String builtInName, int sheetNumber) {
  1060. validateSheetIndex(sheetNumber);
  1061. CTDefinedNames names = workbook.getDefinedNames() == null ? workbook.addNewDefinedNames() : workbook.getDefinedNames();
  1062. CTDefinedName nameRecord = names.addNewDefinedName();
  1063. nameRecord.setName(builtInName);
  1064. nameRecord.setLocalSheetId(sheetNumber);
  1065. XSSFName name = new XSSFName(nameRecord, this);
  1066. for (XSSFName nr : namedRanges) {
  1067. if (nr.equals(name))
  1068. throw new POIXMLException("Builtin (" + builtInName
  1069. + ") already exists for sheet (" + sheetNumber + ")");
  1070. }
  1071. namedRanges.add(name);
  1072. return name;
  1073. }
  1074. /**
  1075. * We only set one sheet as selected for compatibility with HSSF.
  1076. */
  1077. public void setSelectedTab(int index) {
  1078. for (int i = 0 ; i < sheets.size() ; ++i) {
  1079. XSSFSheet sheet = sheets.get(i);
  1080. sheet.setSelected(i == index);
  1081. }
  1082. }
  1083. /**
  1084. * Set the sheet name.
  1085. *
  1086. * @param sheetIndex sheet number (0 based)
  1087. * @param sheetname the new sheet name
  1088. * @throws IllegalArgumentException if the name is null or invalid
  1089. * or workbook already contains a sheet with this name
  1090. * @see #createSheet(String)
  1091. * @see org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)
  1092. */
  1093. public void setSheetName(int sheetIndex, String sheetname) {
  1094. validateSheetIndex(sheetIndex);
  1095. // YK: Mimic Excel and silently truncate sheet names longer than 31 characters
  1096. if(sheetname != null && sheetname.length() > 31) sheetname = sheetname.substring(0, 31);
  1097. WorkbookUtil.validateSheetName(sheetname);
  1098. if (containsSheet(sheetname, sheetIndex ))
  1099. throw new IllegalArgumentException( "The workbook already contains a sheet of this name" );
  1100. XSSFFormulaUtils utils = new XSSFFormulaUtils(this);
  1101. utils.updateSheetName(sheetIndex, sheetname);
  1102. workbook.getSheets().getSheetArray(sheetIndex).setName(sheetname);
  1103. }
  1104. /**
  1105. * sets the order of appearance for a given sheet.
  1106. *
  1107. * @param sheetname the name of the sheet to reorder
  1108. * @param pos the position that we want to insert the sheet into (0 based)
  1109. */
  1110. public void setSheetOrder(String sheetname, int pos) {
  1111. int idx = getSheetIndex(sheetname);
  1112. sheets.add(pos, sheets.remove(idx));
  1113. // Reorder CTSheets
  1114. CTSheets ct = workbook.getSheets();
  1115. XmlObject cts = ct.getSheetArray(idx).copy();
  1116. workbook.getSheets().removeSheet(idx);
  1117. CTSheet newcts = ct.insertNewSheet(pos);
  1118. newcts.set(cts);
  1119. //notify sheets
  1120. for(int i=0; i < sheets.size(); i++) {
  1121. sheets.get(i).sheet = ct.getSheetArray(i);
  1122. }
  1123. }
  1124. /**
  1125. * marshal named ranges from the {@link #namedRanges} collection to the underlying CTWorkbook bean
  1126. */
  1127. private void saveNamedRanges(){
  1128. // Named ranges
  1129. if(namedRanges.size() > 0) {
  1130. CTDefinedNames names = CTDefinedNames.Factory.newInstance();
  1131. CTDefinedName[] nr = new CTDefinedName[namedRanges.size()];
  1132. int i = 0;
  1133. for(XSSFName name : namedRanges) {
  1134. nr[i] = name.getCTName();
  1135. i++;
  1136. }
  1137. names.setDefinedNameArray(nr);
  1138. workbook.setDefinedNames(names);
  1139. } else {
  1140. if(workbook.isSetDefinedNames()) {
  1141. workbook.unsetDefinedNames();
  1142. }
  1143. }
  1144. }
  1145. private void saveCalculationChain(){
  1146. if(calcChain != null){
  1147. int count = calcChain.getCTCalcChain().sizeOfCArray();
  1148. if(count == 0){
  1149. removeRelation(calcChain);
  1150. calcChain = null;
  1151. }
  1152. }
  1153. }
  1154. @Override
  1155. protected void commit() throws IOException {
  1156. saveNamedRanges();
  1157. saveCalculationChain();
  1158. XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
  1159. xmlOptions.setSaveSyntheticDocumentElement(new QName(CTWorkbook.type.getName().getNamespaceURI(), "workbook"));
  1160. Map<String, String> map = new HashMap<String, String>();
  1161. map.put(STRelationshipId.type.getName().getNamespaceURI(), "r");
  1162. xmlOptions.setSaveSuggestedPrefixes(map);
  1163. PackagePart part = getPackagePart();
  1164. OutputStream out = part.getOutputStream();
  1165. workbook.save(out, xmlOptions);
  1166. out.close();
  1167. }
  1168. /**
  1169. * Returns SharedStringsTable - tha cache of string for this workbook
  1170. *
  1171. * @return the shared string table
  1172. */
  1173. @Internal
  1174. public SharedStringsTable getSharedStringSource() {
  1175. return this.sharedStringSource;
  1176. }
  1177. /**
  1178. * Return a object representing a collection of shared objects used for styling content,
  1179. * e.g. fonts, cell styles, colors, etc.
  1180. */
  1181. public StylesTable getStylesSource() {
  1182. return this.stylesSource;
  1183. }
  1184. /**
  1185. * Returns the Theme of current workbook.
  1186. */
  1187. public ThemesTable getTheme() {
  1188. return theme;
  1189. }
  1190. /**
  1191. * Returns an object that handles instantiating concrete
  1192. * classes of the various instances for XSSF.
  1193. */
  1194. public XSSFCreationHelper getCreationHelper() {
  1195. if(_creationHelper == null) _creationHelper = new XSSFCreationHelper(this);
  1196. return _creationHelper;
  1197. }
  1198. /**
  1199. * Determines whether a workbook contains the provided sheet name.
  1200. * For the purpose of comparison, long names are truncated to 31 chars.
  1201. *
  1202. * @param name the name to test (case insensitive match)
  1203. * @param excludeSheetIdx the sheet to exclude from the check or -1 to include all sheets in the check.
  1204. * @return true if the sheet contains the name, false otherwise.
  1205. */
  1206. @SuppressWarnings("deprecation") // getXYZArray() array accessors are deprecated
  1207. private boolean containsSheet(String name, int excludeSheetIdx) {
  1208. CTSheet[] ctSheetArray = workbook.getSheets().getSheetArray();
  1209. if (name.length() > MAX_SENSITIVE_SHEET_NAME_LEN) {
  1210. name = name.substring(0, MAX_SENSITIVE_SHEET_NAME_LEN);
  1211. }
  1212. for (int i = 0; i < ctSheetArray.length; i++) {
  1213. String ctName = ctSheetArray[i].getName();
  1214. if (ctName.length() > MAX_SENSITIVE_SHEET_NAME_LEN) {
  1215. ctName = ctName.substring(0, MAX_SENSITIVE_SHEET_NAME_LEN);
  1216. }
  1217. if (excludeSheetIdx != i && name.equalsIgnoreCase(ctName))
  1218. return true;
  1219. }
  1220. return false;
  1221. }
  1222. /**
  1223. * Gets a boolean value that indicates whether the date systems used in the workbook starts in 1904.
  1224. * <p>
  1225. * The default value is false, meaning that the workbook uses the 1900 date system,
  1226. * where 1/1/1900 is the first day in the system..
  1227. * </p>
  1228. * @return true if the date systems used in the workbook starts in 1904
  1229. */
  1230. protected boolean isDate1904(){
  1231. CTWorkbookPr workbookPr = workbook.getWorkbookPr();
  1232. return workbookPr != null && workbookPr.getDate1904();
  1233. }
  1234. /**
  1235. * Get the document's embedded files.
  1236. */
  1237. public List<PackagePart> getAllEmbedds() throws OpenXML4JException {
  1238. List<PackagePart> embedds = new LinkedList<PackagePart>();
  1239. for(XSSFSheet sheet : sheets){
  1240. // Get the embeddings for the workbook
  1241. for(PackageRelationship rel : sheet.getPackagePart().getRelationshipsByType(XSSFRelation.OLEEMBEDDINGS.getRelation())) {
  1242. embedds.add( sheet.getPackagePart().getRelatedPart(rel) );
  1243. }
  1244. for(PackageRelationship rel : sheet.getPackagePart().getRelationshipsByType(XSSFRelation.PACKEMBEDDINGS.getRelation())) {
  1245. embedds.add( sheet.getPackagePart().getRelatedPart(rel) );
  1246. }
  1247. }
  1248. return embedds;
  1249. }
  1250. public boolean isHidden() {
  1251. throw new RuntimeException("Not implemented yet");
  1252. }
  1253. public void setHidden(boolean hiddenFlag) {
  1254. throw new RuntimeException("Not implemented yet");
  1255. }
  1256. /**
  1257. * Check whether a sheet is hidden.
  1258. * <p>
  1259. * Note that a sheet could instead be set to be very hidden, which is different
  1260. * ({@link #isSheetVeryHidden(int)})
  1261. * </p>
  1262. * @param sheetIx Number
  1263. * @return <code>true</code> if sheet is hidden
  1264. */
  1265. public boolean isSheetHidden(int sheetIx) {
  1266. validateSheetIndex(sheetIx);
  1267. CTSheet ctSheet = sheets.get(sheetIx).sheet;
  1268. return ctSheet.getState() == STSheetState.HIDDEN;
  1269. }
  1270. /**
  1271. * Check whether a sheet is very hidden.
  1272. * <p>
  1273. * This is different from the normal hidden status
  1274. * ({@link #isSheetHidden(int)})
  1275. * </p>
  1276. * @param sheetIx sheet index to check
  1277. * @return <code>true</code> if sheet is very hidden
  1278. */
  1279. public boolean isSheetVeryHidden(int sheetIx) {
  1280. validateSheetIndex(sheetIx);
  1281. CTSheet ctSheet = sheets.get(sheetIx).sheet;
  1282. return ctSheet.getState() == STSheetState.VERY_HIDDEN;
  1283. }
  1284. /**
  1285. * Sets the visible state of this sheet.
  1286. * <p>
  1287. * Calling <code>setSheetHidden(sheetIndex, true)</code> is equivalent to
  1288. * <code>setSheetHidden(sheetIndex, Workbook.SHEET_STATE_HIDDEN)</code>.
  1289. * <br/>
  1290. * Calling <code>setSheetHidden(sheetIndex, false)</code> is equivalent to
  1291. * <code>setSheetHidden(sheetIndex, Workbook.SHEET_STATE_VISIBLE)</code>.
  1292. * </p>
  1293. *
  1294. * @param sheetIx the 0-based index of the sheet
  1295. * @param hidden whether this sheet is hidden
  1296. * @see #setSheetHidden(int, int)
  1297. */
  1298. public void setSheetHidden(int sheetIx, boolean hidden) {
  1299. setSheetHidden(sheetIx, hidden ? SHEET_STATE_HIDDEN : SHEET_STATE_VISIBLE);
  1300. }
  1301. /**
  1302. * Hide or unhide a sheet.
  1303. *
  1304. * <ul>
  1305. * <li>0 - visible. </li>
  1306. * <li>1 - hidden. </li>
  1307. * <li>2 - very hidden.</li>
  1308. * </ul>
  1309. * @param sheetIx the sheet index (0-based)
  1310. * @param state one of the following <code>Workbook</code> constants:
  1311. * <code>Workbook.SHEET_STATE_VISIBLE</code>,
  1312. * <code>Workbook.SHEET_STATE_HIDDEN</code>, or
  1313. * <code>Workbook.SHEET_STATE_VERY_HIDDEN</code>.
  1314. * @throws IllegalArgumentException if the supplied sheet index or state is invalid
  1315. */
  1316. public void setSheetHidden(int sheetIx, int state) {
  1317. validateSheetIndex(sheetIx);
  1318. WorkbookUtil.validateSheetState(state);
  1319. CTSheet ctSheet = sheets.get(sheetIx).sheet;
  1320. ctSheet.setState(STSheetState.Enum.forInt(state + 1));
  1321. }
  1322. /**
  1323. * Fired when a formula is deleted from this workbook,
  1324. * for example when calling cell.setCellFormula(null)
  1325. *
  1326. * @see XSSFCell#setCellFormula(String)
  1327. */
  1328. protected void onDeleteFormula(XSSFCell cell){
  1329. if(calcChain != null) {
  1330. int sheetId = (int)cell.getSheet().sheet.getSheetId();
  1331. calcChain.removeItem(sheetId, cell.getReference());
  1332. }
  1333. }
  1334. /**
  1335. * Return the CalculationChain object for this workbook
  1336. * <p>
  1337. * The calculation chain object specifies the order in which the cells in a workbook were last calculated
  1338. * </p>
  1339. *
  1340. * @return the <code>CalculationChain</code> object or <code>null</code> if not defined
  1341. */
  1342. @Internal
  1343. public CalculationChain getCalculationChain(){
  1344. return calcChain;
  1345. }
  1346. /**
  1347. *
  1348. * @return a collection of custom XML mappings defined in this workbook
  1349. */
  1350. public Collection<XSSFMap> getCustomXMLMappings(){
  1351. return mapInfo == null ? new ArrayList<XSSFMap>() : mapInfo.getAllXSSFMaps();
  1352. }
  1353. /**
  1354. *
  1355. * @return the helper class used to query the custom XML mapping defined in this workbook
  1356. */
  1357. @Internal
  1358. public MapInfo getMapInfo(){
  1359. return mapInfo;
  1360. }
  1361. /**
  1362. * Specifies a boolean value that indicates whether structure of workbook is locked. <br/>
  1363. * A value true indicates the structure of the workbook is locked. Worksheets in the workbook can't be moved,
  1364. * deleted, hidden, unhidden, or renamed, and new worksheets can't be inserted.<br/>
  1365. * A value of false indicates the structure of the workbook is not locked.<br/>
  1366. *
  1367. * @return true if structure of workbook is locked
  1368. */
  1369. public boolean isStructureLocked() {
  1370. return workbookProtectionPresent() && workbook.getWorkbookProtection().getLockStructure();
  1371. }
  1372. /**
  1373. * Specifies a boolean value that indicates whether the windows that comprise the workbook are locked. <br/>
  1374. * A value of true indicates the workbook windows are locked. Windows are the same size and position each time the
  1375. * workbook is opened.<br/>
  1376. * A value of false indicates the workbook windows are not locked.
  1377. *
  1378. * @return true if windows that comprise the workbook are locked
  1379. */
  1380. public boolean isWindowsLocked() {
  1381. return workbookProtectionPresent() && workbook.getWorkbookProtection().getLockWindows();
  1382. }
  1383. /**
  1384. * Specifies a boolean value that indicates whether the workbook is locked for revisions.
  1385. *
  1386. * @return true if the workbook is locked for revisions.
  1387. */
  1388. public boolean isRevisionLocked() {
  1389. return workbookProtectionPresent() && workbook.getWorkbookProtection().getLockRevision();
  1390. }
  1391. /**
  1392. * Locks the structure of workbook.
  1393. */
  1394. public void lockStructure() {
  1395. createProtectionFieldIfNotPresent();
  1396. workbook.getWorkbookProtection().setLockStructure(true);
  1397. }
  1398. /**
  1399. * Unlocks the structure of workbook.
  1400. */
  1401. public void unLockStructure() {
  1402. createProtectionFieldIfNotPresent();
  1403. workbook.getWorkbookProtection().setLockStructure(false);
  1404. }
  1405. /**
  1406. * Locks the windows that comprise the workbook.
  1407. */
  1408. public void lockWindows() {
  1409. createProtectionFieldIfNotPresent();
  1410. workbook.getWorkbookProtection().setLockWindows(true);
  1411. }
  1412. /**
  1413. * Unlocks the windows that comprise the workbook.
  1414. */
  1415. public void unLockWindows() {
  1416. createProtectionFieldIfNotPresent();
  1417. workbook.getWorkbookProtection().setLockWindows(false);
  1418. }
  1419. /**
  1420. * Locks the workbook for revisions.
  1421. */
  1422. public void lockRevision() {
  1423. createProtectionFieldIfNotPresent();
  1424. workbook.getWorkbookProtection().setLockRevision(true);
  1425. }
  1426. /**
  1427. * Unlocks the workbook for revisions.
  1428. */
  1429. public void unLockRevision() {
  1430. createProtectionFieldIfNotPresent();
  1431. workbook.getWorkbookProtection().setLockRevision(false);
  1432. }
  1433. private boolean workbookProtectionPresent() {
  1434. return workbook.getWorkbookProtection() != null;
  1435. }
  1436. private void createProtectionFieldIfNotPresent() {
  1437. if (workbook.getWorkbookProtection() == null){
  1438. workbook.setWorkbookProtection(CTWorkbookProtection.Factory.newInstance());
  1439. }
  1440. }
  1441. /**
  1442. *
  1443. * Returns the locator of user-defined functions.
  1444. * <p>
  1445. * The default instance extends the built-in functions with the Excel Analysis Tool Pack.
  1446. * To set / evaluate custom functions you need to register them as follows:
  1447. *
  1448. *
  1449. *
  1450. * </p>
  1451. * @return wrapped instance of UDFFinder that allows seeking functions both by index and name
  1452. */
  1453. /*package*/ UDFFinder getUDFFinder() {
  1454. return _udfFinder;
  1455. }
  1456. /**
  1457. * Register a new toolpack in this workbook.
  1458. *
  1459. * @param toopack the toolpack to register
  1460. */
  1461. public void addToolPack(UDFFinder toopack){
  1462. _udfFinder.add(toopack);
  1463. }
  1464. /**
  1465. * Whether the application shall perform a full recalculation when the workbook is opened.
  1466. * <p>
  1467. * Typically you want to force formula recalculation when you modify cell formulas or values
  1468. * of a workbook previously created by Excel. When set to true, this flag will tell Excel
  1469. * that it needs to recalculate all formulas in the workbook the next time the file is opened.
  1470. * </p>
  1471. * <p>
  1472. * Note, that recalculation updates cached formula results and, thus, modifies the workbook.
  1473. * Depending on the version, Excel may prompt you with "Do you want to save the changes in <em>filename</em>?"
  1474. * on close.
  1475. * </p>
  1476. *
  1477. * @param value true if the application will perform a full recalculation of
  1478. * workbook values when the workbook is opened
  1479. * @since 3.8
  1480. */
  1481. public void setForceFormulaRecalculation(boolean value){
  1482. CTWorkbook ctWorkbook = getCTWorkbook();
  1483. CTCalcPr calcPr = ctWorkbook.isSetCalcPr() ? ctWorkbook.getCalcPr() : ctWorkbook.addNewCalcPr();
  1484. // when set to 0, will tell Excel that it needs to recalculate all formulas
  1485. // in the workbook the next time the file is opened.
  1486. calcPr.setCalcId(0);
  1487. if(value && calcPr.getCalcMode() == STCalcMode.MANUAL) {
  1488. calcPr.setCalcMode(STCalcMode.AUTO);
  1489. }
  1490. }
  1491. /**
  1492. * Whether Excel will be asked to recalculate all formulas when the workbook is opened.
  1493. *
  1494. * @since 3.8
  1495. */
  1496. public boolean getForceFormulaRecalculation(){
  1497. CTWorkbook ctWorkbook = getCTWorkbook();
  1498. CTCalcPr calcPr = ctWorkbook.getCalcPr();
  1499. return calcPr != null && calcPr.getCalcId() != 0;
  1500. }
  1501. }