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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  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.IOException;
  19. import java.io.InputStream;
  20. import java.io.OutputStream;
  21. import java.util.*;
  22. import java.util.regex.Pattern;
  23. import javax.xml.namespace.QName;
  24. import org.apache.poi.POIXMLDocument;
  25. import org.apache.poi.POIXMLDocumentPart;
  26. import org.apache.poi.POIXMLException;
  27. import org.apache.poi.POIXMLProperties;
  28. import org.apache.poi.hssf.record.formula.SheetNameFormatter;
  29. import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
  30. import org.apache.poi.openxml4j.opc.OPCPackage;
  31. import org.apache.poi.openxml4j.opc.PackagePart;
  32. import org.apache.poi.openxml4j.opc.PackagePartName;
  33. import org.apache.poi.openxml4j.opc.PackageRelationship;
  34. import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
  35. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  36. import org.apache.poi.openxml4j.opc.TargetMode;
  37. import org.apache.poi.ss.usermodel.Row;
  38. import org.apache.poi.ss.usermodel.Sheet;
  39. import org.apache.poi.ss.usermodel.Workbook;
  40. import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
  41. import org.apache.poi.ss.util.CellReference;
  42. import org.apache.poi.util.IOUtils;
  43. import org.apache.poi.util.POILogFactory;
  44. import org.apache.poi.util.POILogger;
  45. import org.apache.poi.util.PackageHelper;
  46. import org.apache.poi.xssf.model.CalculationChain;
  47. import org.apache.poi.xssf.model.SharedStringsTable;
  48. import org.apache.poi.xssf.model.StylesTable;
  49. import org.apache.poi.xssf.model.MapInfo;
  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. * The underlying XML bean
  68. */
  69. private CTWorkbook workbook;
  70. /**
  71. * this holds the XSSFSheet objects attached to this workbook
  72. */
  73. private List<XSSFSheet> sheets;
  74. /**
  75. * this holds the XSSFName objects attached to this workbook
  76. */
  77. private List<XSSFName> namedRanges;
  78. /**
  79. * shared string table - a cache of strings in this workbook
  80. */
  81. private SharedStringsTable sharedStringSource;
  82. /**
  83. * A collection of shared objects used for styling content,
  84. * e.g. fonts, cell styles, colors, etc.
  85. */
  86. private StylesTable stylesSource;
  87. /**
  88. * TODO
  89. */
  90. private CalculationChain calcChain;
  91. /**
  92. * A collection of custom XML mappings
  93. */
  94. private MapInfo mapInfo;
  95. /**
  96. * Used to keep track of the data formatter so that all
  97. * createDataFormatter calls return the same one for a given
  98. * book. This ensures that updates from one places is visible
  99. * someplace else.
  100. */
  101. private XSSFDataFormat formatter;
  102. /**
  103. * The policy to apply in the event of missing or
  104. * blank cells when fetching from a row.
  105. * See {@link org.apache.poi.ss.usermodel.Row.MissingCellPolicy}
  106. */
  107. private MissingCellPolicy _missingCellPolicy = Row.RETURN_NULL_AND_BLANK;
  108. /**
  109. * array of pictures for this workbook
  110. */
  111. private List<XSSFPictureData> pictures;
  112. private static POILogger logger = POILogFactory.getLogger(XSSFWorkbook.class);
  113. /**
  114. * Create a new SpreadsheetML workbook.
  115. */
  116. public XSSFWorkbook() {
  117. super(newPackage());
  118. onWorkbookCreate();
  119. }
  120. /**
  121. * Constructs a XSSFWorkbook object given a OpenXML4J <code>Package</code> object,
  122. * see <a href="http://openxml4j.org/">www.openxml4j.org</a>.
  123. *
  124. * @param pkg the OpenXML4J <code>Package</code> object.
  125. */
  126. public XSSFWorkbook(OPCPackage pkg) throws IOException {
  127. super(ensureWriteAccess(pkg));
  128. //build a tree of POIXMLDocumentParts, this workbook being the root
  129. load(XSSFFactory.getInstance());
  130. }
  131. public XSSFWorkbook(InputStream is) throws IOException {
  132. super(PackageHelper.open(is));
  133. //build a tree of POIXMLDocumentParts, this workbook being the root
  134. load(XSSFFactory.getInstance());
  135. }
  136. /**
  137. * Constructs a XSSFWorkbook object given a file name.
  138. *
  139. * @param path the file name.
  140. */
  141. public XSSFWorkbook(String path) throws IOException {
  142. this(openPackage(path));
  143. }
  144. @Override
  145. protected void onDocumentRead() throws IOException {
  146. try {
  147. WorkbookDocument doc = WorkbookDocument.Factory.parse(getPackagePart().getInputStream());
  148. this.workbook = doc.getWorkbook();
  149. Map<String, XSSFSheet> shIdMap = new HashMap<String, XSSFSheet>();
  150. for(POIXMLDocumentPart p : getRelations()){
  151. if(p instanceof SharedStringsTable) sharedStringSource = (SharedStringsTable)p;
  152. else if(p instanceof StylesTable) stylesSource = (StylesTable)p;
  153. else if(p instanceof CalculationChain) calcChain = (CalculationChain)p;
  154. else if(p instanceof MapInfo) mapInfo = (MapInfo)p;
  155. else if (p instanceof XSSFSheet) {
  156. shIdMap.put(p.getPackageRelationship().getId(), (XSSFSheet)p);
  157. }
  158. }
  159. if(sharedStringSource == null) {
  160. //Create SST if it is missing
  161. sharedStringSource = (SharedStringsTable)createRelationship(XSSFRelation.SHARED_STRINGS, XSSFFactory.getInstance());
  162. }
  163. // Load individual sheets. The order of sheets is defined by the order of CTSheet elements in the workbook
  164. sheets = new ArrayList<XSSFSheet>(shIdMap.size());
  165. for (CTSheet ctSheet : this.workbook.getSheets().getSheetArray()) {
  166. XSSFSheet sh = shIdMap.get(ctSheet.getId());
  167. if(sh == null) {
  168. logger.log(POILogger.WARN, "Sheet with name " + ctSheet.getName() + " and r:id " + ctSheet.getId()+ " was defined, but didn't exist in package, skipping");
  169. continue;
  170. }
  171. sh.sheet = ctSheet;
  172. sh.onDocumentRead();
  173. sheets.add(sh);
  174. }
  175. // Process the named ranges
  176. namedRanges = new ArrayList<XSSFName>();
  177. if(workbook.isSetDefinedNames()) {
  178. for(CTDefinedName ctName : workbook.getDefinedNames().getDefinedNameArray()) {
  179. namedRanges.add(new XSSFName(ctName, this));
  180. }
  181. }
  182. } catch (XmlException e) {
  183. throw new POIXMLException(e);
  184. }
  185. }
  186. /**
  187. * Create a new CTWorkbook with all values set to default
  188. */
  189. private void onWorkbookCreate() {
  190. workbook = CTWorkbook.Factory.newInstance();
  191. // don't EVER use the 1904 date system
  192. CTWorkbookPr workbookPr = workbook.addNewWorkbookPr();
  193. workbookPr.setDate1904(false);
  194. CTBookViews bvs = workbook.addNewBookViews();
  195. CTBookView bv = bvs.addNewWorkbookView();
  196. bv.setActiveTab(0);
  197. workbook.addNewSheets();
  198. POIXMLProperties.ExtendedProperties expProps = getProperties().getExtendedProperties();
  199. expProps.getUnderlyingProperties().setApplication(DOCUMENT_CREATOR);
  200. sharedStringSource = (SharedStringsTable)createRelationship(XSSFRelation.SHARED_STRINGS, XSSFFactory.getInstance());
  201. stylesSource = (StylesTable)createRelationship(XSSFRelation.STYLES, XSSFFactory.getInstance());
  202. namedRanges = new ArrayList<XSSFName>();
  203. sheets = new ArrayList<XSSFSheet>();
  204. }
  205. /**
  206. * Create a new SpreadsheetML package and setup the default minimal content
  207. */
  208. protected static OPCPackage newPackage() {
  209. try {
  210. OPCPackage pkg = OPCPackage.create(PackageHelper.createTempFile());
  211. // Main part
  212. PackagePartName corePartName = PackagingURIHelper.createPartName(XSSFRelation.WORKBOOK.getDefaultFileName());
  213. // Create main part relationship
  214. pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT);
  215. // Create main document part
  216. pkg.createPart(corePartName, XSSFRelation.WORKBOOK.getContentType());
  217. pkg.getPackageProperties().setCreatorProperty(DOCUMENT_CREATOR);
  218. return pkg;
  219. } catch (Exception e){
  220. throw new POIXMLException(e);
  221. }
  222. }
  223. /**
  224. * Return the underlying XML bean
  225. *
  226. * @return the underlying CTWorkbook bean
  227. */
  228. public CTWorkbook getCTWorkbook() {
  229. return this.workbook;
  230. }
  231. /**
  232. * Adds a picture to the workbook.
  233. *
  234. * @param pictureData The bytes of the picture
  235. * @param format The format of the picture.
  236. *
  237. * @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} .
  238. * @see Workbook#PICTURE_TYPE_EMF
  239. * @see Workbook#PICTURE_TYPE_WMF
  240. * @see Workbook#PICTURE_TYPE_PICT
  241. * @see Workbook#PICTURE_TYPE_JPEG
  242. * @see Workbook#PICTURE_TYPE_PNG
  243. * @see Workbook#PICTURE_TYPE_DIB
  244. * @see #getAllPictures()
  245. */
  246. public int addPicture(byte[] pictureData, int format) {
  247. int imageNumber = getAllPictures().size() + 1;
  248. XSSFPictureData img = (XSSFPictureData)createRelationship(XSSFPictureData.RELATIONS[format], XSSFFactory.getInstance(), imageNumber, true);
  249. try {
  250. OutputStream out = img.getPackagePart().getOutputStream();
  251. out.write(pictureData);
  252. out.close();
  253. } catch (IOException e){
  254. throw new POIXMLException(e);
  255. }
  256. pictures.add(img);
  257. return imageNumber - 1;
  258. }
  259. /**
  260. * Adds a picture to the workbook.
  261. *
  262. * @param is The sream to read image from
  263. * @param format The format of the picture.
  264. *
  265. * @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} .
  266. * @see Workbook#PICTURE_TYPE_EMF
  267. * @see Workbook#PICTURE_TYPE_WMF
  268. * @see Workbook#PICTURE_TYPE_PICT
  269. * @see Workbook#PICTURE_TYPE_JPEG
  270. * @see Workbook#PICTURE_TYPE_PNG
  271. * @see Workbook#PICTURE_TYPE_DIB
  272. * @see #getAllPictures()
  273. */
  274. public int addPicture(InputStream is, int format) throws IOException {
  275. int imageNumber = getAllPictures().size() + 1;
  276. XSSFPictureData img = (XSSFPictureData)createRelationship(XSSFPictureData.RELATIONS[format], XSSFFactory.getInstance(), imageNumber, true);
  277. OutputStream out = img.getPackagePart().getOutputStream();
  278. IOUtils.copy(is, out);
  279. out.close();
  280. pictures.add(img);
  281. return imageNumber - 1;
  282. }
  283. /**
  284. * Create an XSSFSheet from an existing sheet in the XSSFWorkbook.
  285. * The cloned sheet is a deep copy of the original.
  286. *
  287. * @return XSSFSheet representing the cloned sheet.
  288. * @throws IllegalArgumentException if the sheet index in invalid
  289. * @throws POIXMLException if there were errors when cloning
  290. */
  291. public XSSFSheet cloneSheet(int sheetNum) {
  292. validateSheetIndex(sheetNum);
  293. XSSFSheet srcSheet = sheets.get(sheetNum);
  294. String srcName = srcSheet.getSheetName();
  295. String clonedName = getUniqueSheetName(srcName);
  296. XSSFSheet clonedSheet = createSheet(clonedName);
  297. try {
  298. ByteArrayOutputStream out = new ByteArrayOutputStream();
  299. srcSheet.write(out);
  300. clonedSheet.read(new ByteArrayInputStream(out.toByteArray()));
  301. } catch (IOException e){
  302. throw new POIXMLException("Failed to clone sheet", e);
  303. }
  304. CTWorksheet ct = clonedSheet.getCTWorksheet();
  305. if(ct.isSetDrawing()) {
  306. logger.log(POILogger.WARN, "Cloning sheets with drawings is not yet supported.");
  307. ct.unsetDrawing();
  308. }
  309. if(ct.isSetLegacyDrawing()) {
  310. logger.log(POILogger.WARN, "Cloning sheets with comments is not yet supported.");
  311. ct.unsetLegacyDrawing();
  312. }
  313. clonedSheet.setSelected(false);
  314. return clonedSheet;
  315. }
  316. /**
  317. * Generate a valid sheet name based on the existing one. Used when cloning sheets.
  318. *
  319. * @param srcName the original sheet name to
  320. * @return clone sheet name
  321. */
  322. private String getUniqueSheetName(String srcName) {
  323. int uniqueIndex = 2;
  324. String baseName = srcName;
  325. int bracketPos = srcName.lastIndexOf('(');
  326. if (bracketPos > 0 && srcName.endsWith(")")) {
  327. String suffix = srcName.substring(bracketPos + 1, srcName.length() - ")".length());
  328. try {
  329. uniqueIndex = Integer.parseInt(suffix.trim());
  330. uniqueIndex++;
  331. baseName = srcName.substring(0, bracketPos).trim();
  332. } catch (NumberFormatException e) {
  333. // contents of brackets not numeric
  334. }
  335. }
  336. while (true) {
  337. // Try and find the next sheet name that is unique
  338. String index = Integer.toString(uniqueIndex++);
  339. String name;
  340. if (baseName.length() + index.length() + 2 < 31) {
  341. name = baseName + " (" + index + ")";
  342. } else {
  343. name = baseName.substring(0, 31 - index.length() - 2) + "(" + index + ")";
  344. }
  345. //If the sheet name is unique, then set it otherwise move on to the next number.
  346. if (getSheetIndex(name) == -1) {
  347. return name;
  348. }
  349. }
  350. }
  351. /**
  352. * Create a new XSSFCellStyle and add it to the workbook's style table
  353. *
  354. * @return the new XSSFCellStyle object
  355. */
  356. public XSSFCellStyle createCellStyle() {
  357. return stylesSource.createCellStyle();
  358. }
  359. /**
  360. * Returns the instance of XSSFDataFormat for this workbook.
  361. *
  362. * @return the XSSFDataFormat object
  363. * @see org.apache.poi.ss.usermodel.DataFormat
  364. */
  365. public XSSFDataFormat createDataFormat() {
  366. if (formatter == null)
  367. formatter = new XSSFDataFormat(stylesSource);
  368. return formatter;
  369. }
  370. /**
  371. * Create a new Font and add it to the workbook's font table
  372. *
  373. * @return new font object
  374. */
  375. public XSSFFont createFont() {
  376. XSSFFont font = new XSSFFont();
  377. font.putFont(stylesSource);
  378. return font;
  379. }
  380. public XSSFName createName() {
  381. XSSFName name = new XSSFName(CTDefinedName.Factory.newInstance(), this);
  382. namedRanges.add(name);
  383. return name;
  384. }
  385. /**
  386. * Create an XSSFSheet for this workbook, adds it to the sheets and returns
  387. * the high level representation. Use this to create new sheets.
  388. *
  389. * @return XSSFSheet representing the new sheet.
  390. */
  391. public XSSFSheet createSheet() {
  392. String sheetname = "Sheet" + (sheets.size());
  393. int idx = 0;
  394. while(getSheet(sheetname) != null) {
  395. sheetname = "Sheet" + idx;
  396. idx++;
  397. }
  398. return createSheet(sheetname);
  399. }
  400. /**
  401. * Create an XSSFSheet for this workbook, adds it to the sheets and returns
  402. * the high level representation. Use this to create new sheets.
  403. *
  404. * @param sheetname sheetname to set for the sheet, can't be duplicate, greater than 31 chars or contain /\?*[]
  405. * @return XSSFSheet representing the new sheet.
  406. * @throws IllegalArgumentException if the sheetname is invalid or the workbook already contains a sheet of this name
  407. */
  408. public XSSFSheet createSheet(String sheetname) {
  409. if (containsSheet( sheetname, sheets.size() ))
  410. throw new IllegalArgumentException( "The workbook already contains a sheet of this name");
  411. CTSheet sheet = addSheet(sheetname);
  412. int sheetNumber = 1;
  413. for(XSSFSheet sh : sheets) sheetNumber = (int)Math.max(sh.sheet.getSheetId() + 1, sheetNumber);
  414. XSSFSheet wrapper = (XSSFSheet)createRelationship(XSSFRelation.WORKSHEET, XSSFFactory.getInstance(), sheetNumber);
  415. wrapper.sheet = sheet;
  416. sheet.setId(wrapper.getPackageRelationship().getId());
  417. sheet.setSheetId(sheetNumber);
  418. if(sheets.size() == 0) wrapper.setSelected(true);
  419. sheets.add(wrapper);
  420. return wrapper;
  421. }
  422. protected XSSFDialogsheet createDialogsheet(String sheetname, CTDialogsheet dialogsheet) {
  423. XSSFSheet sheet = createSheet(sheetname);
  424. return new XSSFDialogsheet(sheet);
  425. }
  426. private CTSheet addSheet(String sheetname) {
  427. validateSheetName(sheetname);
  428. CTSheet sheet = workbook.getSheets().addNewSheet();
  429. sheet.setName(sheetname);
  430. return sheet;
  431. }
  432. /**
  433. * Finds a font that matches the one with the supplied attributes
  434. */
  435. public XSSFFont findFont(short boldWeight, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) {
  436. return stylesSource.findFont(boldWeight, color, fontHeight, name, italic, strikeout, typeOffset, underline);
  437. }
  438. /**
  439. * Convenience method to get the active sheet. The active sheet is is the sheet
  440. * which is currently displayed when the workbook is viewed in Excel.
  441. * 'Selected' sheet(s) is a distinct concept.
  442. */
  443. public int getActiveSheetIndex() {
  444. //activeTab (Active Sheet Index) Specifies an unsignedInt
  445. //that contains the index to the active sheet in this book view.
  446. return (int)workbook.getBookViews().getWorkbookViewArray(0).getActiveTab();
  447. }
  448. /**
  449. * Gets all pictures from the Workbook.
  450. *
  451. * @return the list of pictures (a list of {@link XSSFPictureData} objects.)
  452. * @see #addPicture(byte[], int)
  453. */
  454. public List<XSSFPictureData> getAllPictures() {
  455. if(pictures == null) {
  456. //In OOXML pictures are referred to in sheets,
  457. //dive into sheet's relations, select drawings and their images
  458. pictures = new ArrayList<XSSFPictureData>();
  459. for(XSSFSheet sh : sheets){
  460. for(POIXMLDocumentPart dr : sh.getRelations()){
  461. if(dr instanceof XSSFDrawing){
  462. for(POIXMLDocumentPart img : dr.getRelations()){
  463. if(img instanceof XSSFPictureData){
  464. pictures.add((XSSFPictureData)img);
  465. }
  466. }
  467. }
  468. }
  469. }
  470. }
  471. return pictures;
  472. }
  473. /**
  474. * gGet the cell style object at the given index
  475. *
  476. * @param idx index within the set of styles
  477. * @return XSSFCellStyle object at the index
  478. */
  479. public XSSFCellStyle getCellStyleAt(short idx) {
  480. return stylesSource.getStyleAt(idx);
  481. }
  482. /**
  483. * Get the font at the given index number
  484. *
  485. * @param idx index number
  486. * @return XSSFFont at the index
  487. */
  488. public XSSFFont getFontAt(short idx) {
  489. return stylesSource.getFontAt(idx);
  490. }
  491. public XSSFName getName(String name) {
  492. int nameIndex = getNameIndex(name);
  493. if (nameIndex < 0) {
  494. return null;
  495. }
  496. return namedRanges.get(nameIndex);
  497. }
  498. public XSSFName getNameAt(int nameIndex) {
  499. int nNames = namedRanges.size();
  500. if (nNames < 1) {
  501. throw new IllegalStateException("There are no defined names in this workbook");
  502. }
  503. if (nameIndex < 0 || nameIndex > nNames) {
  504. throw new IllegalArgumentException("Specified name index " + nameIndex
  505. + " is outside the allowable range (0.." + (nNames-1) + ").");
  506. }
  507. return namedRanges.get(nameIndex);
  508. }
  509. /**
  510. * Gets the named range index by his name
  511. * <i>Note:</i>Excel named ranges are case-insensitive and
  512. * this method performs a case-insensitive search.
  513. *
  514. * @param name named range name
  515. * @return named range index
  516. */
  517. public int getNameIndex(String name) {
  518. int i = 0;
  519. for(XSSFName nr : namedRanges) {
  520. if(nr.getNameName().equals(name)) {
  521. return i;
  522. }
  523. i++;
  524. }
  525. return -1;
  526. }
  527. /**
  528. * Get the number of styles the workbook contains
  529. *
  530. * @return count of cell styles
  531. */
  532. public short getNumCellStyles() {
  533. return (short) (stylesSource).getNumCellStyles();
  534. }
  535. /**
  536. * Get the number of fonts in the this workbook
  537. *
  538. * @return number of fonts
  539. */
  540. public short getNumberOfFonts() {
  541. return (short)stylesSource.getFonts().size();
  542. }
  543. /**
  544. * Get the number of named ranges in the this workbook
  545. *
  546. * @return number of named ranges
  547. */
  548. public int getNumberOfNames() {
  549. return namedRanges.size();
  550. }
  551. /**
  552. * Get the number of worksheets in the this workbook
  553. *
  554. * @return number of worksheets
  555. */
  556. public int getNumberOfSheets() {
  557. return sheets.size();
  558. }
  559. /**
  560. * Retrieves the reference for the printarea of the specified sheet, the sheet name is appended to the reference even if it was not specified.
  561. * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java)
  562. * @return String Null if no print area has been defined
  563. */
  564. public String getPrintArea(int sheetIndex) {
  565. XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
  566. if (name == null) return null;
  567. //adding one here because 0 indicates a global named region; doesnt make sense for print areas
  568. return name.getRefersToFormula();
  569. }
  570. /**
  571. * Get sheet with the given name (case insensitive match)
  572. *
  573. * @param name of the sheet
  574. * @return XSSFSheet with the name provided or <code>null</code> if it does not exist
  575. */
  576. public XSSFSheet getSheet(String name) {
  577. for (XSSFSheet sheet : sheets) {
  578. if (name.equalsIgnoreCase(sheet.getSheetName())) {
  579. return sheet;
  580. }
  581. }
  582. return null;
  583. }
  584. /**
  585. * Get the XSSFSheet object at the given index.
  586. *
  587. * @param index of the sheet number (0-based physical & logical)
  588. * @return XSSFSheet at the provided index
  589. * @throws IllegalArgumentException if the index is out of range (index
  590. * &lt; 0 || index &gt;= getNumberOfSheets()).
  591. */
  592. public XSSFSheet getSheetAt(int index) {
  593. validateSheetIndex(index);
  594. return sheets.get(index);
  595. }
  596. /**
  597. * Returns the index of the sheet by his name (case insensitive match)
  598. *
  599. * @param name the sheet name
  600. * @return index of the sheet (0 based) or <tt>-1</tt if not found
  601. */
  602. public int getSheetIndex(String name) {
  603. for (int i = 0 ; i < sheets.size() ; ++i) {
  604. XSSFSheet sheet = sheets.get(i);
  605. if (name.equalsIgnoreCase(sheet.getSheetName())) {
  606. return i;
  607. }
  608. }
  609. return -1;
  610. }
  611. /**
  612. * Returns the index of the given sheet
  613. *
  614. * @param sheet the sheet to look up
  615. * @return index of the sheet (0 based). <tt>-1</tt> if not found
  616. */
  617. public int getSheetIndex(Sheet sheet) {
  618. int idx = 0;
  619. for(XSSFSheet sh : sheets){
  620. if(sh == sheet) return idx;
  621. idx++;
  622. }
  623. return -1;
  624. }
  625. /**
  626. * Get the sheet name
  627. *
  628. * @param sheetIx Number
  629. * @return Sheet name
  630. */
  631. public String getSheetName(int sheetIx) {
  632. validateSheetIndex(sheetIx);
  633. return sheets.get(sheetIx).getSheetName();
  634. }
  635. /**
  636. * Allows foreach loops:
  637. * <pre><code>
  638. * XSSFWorkbook wb = new XSSFWorkbook(package);
  639. * for(XSSFSheet sheet : wb){
  640. *
  641. * }
  642. * </code></pre>
  643. */
  644. public Iterator<XSSFSheet> iterator() {
  645. return sheets.iterator();
  646. }
  647. /**
  648. * Are we a normal workbook (.xlsx), or a
  649. * macro enabled workbook (.xlsm)?
  650. */
  651. public boolean isMacroEnabled() {
  652. return getPackagePart().getContentType().equals(XSSFRelation.MACROS_WORKBOOK.getContentType());
  653. }
  654. public void removeName(int nameIndex) {
  655. namedRanges.remove(nameIndex);
  656. }
  657. public void removeName(String name) {
  658. for (int i = 0; i < namedRanges.size(); i++) {
  659. XSSFName nm = namedRanges.get(i);
  660. if(nm.getNameName().equalsIgnoreCase(name)) {
  661. removeName(i);
  662. return;
  663. }
  664. }
  665. throw new IllegalArgumentException("Named range was not found: " + name);
  666. }
  667. /**
  668. * Delete the printarea for the sheet specified
  669. *
  670. * @param sheetIndex 0-based sheet index (0 = First Sheet)
  671. */
  672. public void removePrintArea(int sheetIndex) {
  673. int cont = 0;
  674. for (XSSFName name : namedRanges) {
  675. if (name.getNameName().equals(XSSFName.BUILTIN_PRINT_AREA) && name.getSheetIndex() == sheetIndex) {
  676. namedRanges.remove(cont);
  677. break;
  678. }
  679. cont++;
  680. }
  681. }
  682. /**
  683. * Removes sheet at the given index.<p/>
  684. *
  685. * Care must be taken if the removed sheet is the currently active or only selected sheet in
  686. * the workbook. There are a few situations when Excel must have a selection and/or active
  687. * sheet. (For example when printing - see Bug 40414).<br/>
  688. *
  689. * This method makes sure that if the removed sheet was active, another sheet will become
  690. * active in its place. Furthermore, if the removed sheet was the only selected sheet, another
  691. * sheet will become selected. The newly active/selected sheet will have the same index, or
  692. * one less if the removed sheet was the last in the workbook.
  693. *
  694. * @param index of the sheet (0-based)
  695. */
  696. public void removeSheetAt(int index) {
  697. validateSheetIndex(index);
  698. onSheetDelete(index);
  699. XSSFSheet sheet = getSheetAt(index);
  700. removeRelation(sheet);
  701. sheets.remove(index);
  702. }
  703. /**
  704. * Gracefully remove references to the sheet being deleted
  705. *
  706. * @param index the 0-based index of the sheet to delete
  707. */
  708. private void onSheetDelete(int index) {
  709. //delete the CTSheet reference from workbook.xml
  710. workbook.getSheets().removeSheet(index);
  711. //calculation chain is auxilary, remove it as it may contain orfan references to deleted cells
  712. if(calcChain != null) {
  713. removeRelation(calcChain);
  714. calcChain = null;
  715. }
  716. //adjust indices of names ranges
  717. for (Iterator<XSSFName> it = namedRanges.iterator(); it.hasNext();) {
  718. XSSFName nm = it.next();
  719. CTDefinedName ct = nm.getCTName();
  720. if(!ct.isSetLocalSheetId()) continue;
  721. if (ct.getLocalSheetId() == index) {
  722. it.remove();
  723. } else if (ct.getLocalSheetId() > index){
  724. // Bump down by one, so still points at the same sheet
  725. ct.setLocalSheetId(ct.getLocalSheetId()-1);
  726. }
  727. }
  728. }
  729. /**
  730. * Retrieves the current policy on what to do when
  731. * getting missing or blank cells from a row.
  732. * The default is to return blank and null cells.
  733. * {@link MissingCellPolicy}
  734. */
  735. public MissingCellPolicy getMissingCellPolicy() {
  736. return _missingCellPolicy;
  737. }
  738. /**
  739. * Sets the policy on what to do when
  740. * getting missing or blank cells from a row.
  741. * This will then apply to all calls to
  742. * {@link Row#getCell(int)}}. See
  743. * {@link MissingCellPolicy}
  744. */
  745. public void setMissingCellPolicy(MissingCellPolicy missingCellPolicy) {
  746. _missingCellPolicy = missingCellPolicy;
  747. }
  748. /**
  749. * Convenience method to set the active sheet. The active sheet is is the sheet
  750. * which is currently displayed when the workbook is viewed in Excel.
  751. * 'Selected' sheet(s) is a distinct concept.
  752. */
  753. public void setActiveSheet(int index) {
  754. validateSheetIndex(index);
  755. //activeTab (Active Sheet Index) Specifies an unsignedInt that contains the index to the active sheet in this book view.
  756. CTBookView[] arrayBook = workbook.getBookViews().getWorkbookViewArray();
  757. for (int i = 0; i < arrayBook.length; i++) {
  758. workbook.getBookViews().getWorkbookViewArray(i).setActiveTab(index);
  759. }
  760. }
  761. /**
  762. * Validate sheet index
  763. *
  764. * @param index the index to validate
  765. * @throws IllegalArgumentException if the index is out of range (index
  766. * &lt; 0 || index &gt;= getNumberOfSheets()).
  767. */
  768. private void validateSheetIndex(int index) {
  769. int lastSheetIx = sheets.size() - 1;
  770. if (index < 0 || index > lastSheetIx) {
  771. throw new IllegalArgumentException("Sheet index ("
  772. + index +") is out of range (0.." + lastSheetIx + ")");
  773. }
  774. }
  775. /**
  776. * Gets the first tab that is displayed in the list of tabs in excel.
  777. *
  778. * @return integer that contains the index to the active sheet in this book view.
  779. */
  780. public int getFirstVisibleTab() {
  781. CTBookViews bookViews = workbook.getBookViews();
  782. CTBookView bookView = bookViews.getWorkbookViewArray(0);
  783. return (short) bookView.getActiveTab();
  784. }
  785. /**
  786. * Sets the first tab that is displayed in the list of tabs in excel.
  787. *
  788. * @param index integer that contains the index to the active sheet in this book view.
  789. */
  790. public void setFirstVisibleTab(int index) {
  791. CTBookViews bookViews = workbook.getBookViews();
  792. CTBookView bookView= bookViews.getWorkbookViewArray(0);
  793. bookView.setActiveTab(index);
  794. }
  795. /**
  796. * Sets the printarea for the sheet provided
  797. * <p>
  798. * i.e. Reference = $A$1:$B$2
  799. * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java)
  800. * @param reference Valid name Reference for the Print Area
  801. */
  802. public void setPrintArea(int sheetIndex, String reference) {
  803. XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
  804. if (name == null) {
  805. name = createBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
  806. namedRanges.add(name);
  807. }
  808. //short externSheetIndex = getWorkbook().checkExternSheet(sheetIndex);
  809. //name.setExternSheetNumber(externSheetIndex);
  810. String[] parts = COMMA_PATTERN.split(reference);
  811. StringBuffer sb = new StringBuffer(32);
  812. for (int i = 0; i < parts.length; i++) {
  813. if(i>0) {
  814. sb.append(",");
  815. }
  816. SheetNameFormatter.appendFormat(sb, getSheetName(sheetIndex));
  817. sb.append("!");
  818. sb.append(parts[i]);
  819. }
  820. name.setRefersToFormula(sb.toString());
  821. }
  822. /**
  823. * For the Convenience of Java Programmers maintaining pointers.
  824. * @see #setPrintArea(int, String)
  825. * @param sheetIndex Zero-based sheet index (0 = First Sheet)
  826. * @param startColumn Column to begin printarea
  827. * @param endColumn Column to end the printarea
  828. * @param startRow Row to begin the printarea
  829. * @param endRow Row to end the printarea
  830. */
  831. public void setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow) {
  832. String reference=getReferencePrintArea(getSheetName(sheetIndex), startColumn, endColumn, startRow, endRow);
  833. setPrintArea(sheetIndex, reference);
  834. }
  835. /**
  836. * Sets the repeating rows and columns for a sheet.
  837. * <p/>
  838. * To set just repeating columns:
  839. * <pre>
  840. * workbook.setRepeatingRowsAndColumns(0,0,1,-1,-1);
  841. * </pre>
  842. * To set just repeating rows:
  843. * <pre>
  844. * workbook.setRepeatingRowsAndColumns(0,-1,-1,0,4);
  845. * </pre>
  846. * To remove all repeating rows and columns for a sheet.
  847. * <pre>
  848. * workbook.setRepeatingRowsAndColumns(0,-1,-1,-1,-1);
  849. * </pre>
  850. *
  851. * @param sheetIndex 0 based index to sheet.
  852. * @param startColumn 0 based start of repeating columns.
  853. * @param endColumn 0 based end of repeating columns.
  854. * @param startRow 0 based start of repeating rows.
  855. * @param endRow 0 based end of repeating rows.
  856. */
  857. public void setRepeatingRowsAndColumns(int sheetIndex,
  858. int startColumn, int endColumn,
  859. int startRow, int endRow) {
  860. // Check arguments
  861. if ((startColumn == -1 && endColumn != -1) || startColumn < -1 || endColumn < -1 || startColumn > endColumn)
  862. throw new IllegalArgumentException("Invalid column range specification");
  863. if ((startRow == -1 && endRow != -1) || startRow < -1 || endRow < -1 || startRow > endRow)
  864. throw new IllegalArgumentException("Invalid row range specification");
  865. XSSFSheet sheet = getSheetAt(sheetIndex);
  866. boolean removingRange = startColumn == -1 && endColumn == -1 && startRow == -1 && endRow == -1;
  867. XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_TITLE, sheetIndex);
  868. if (removingRange) {
  869. if(name != null)namedRanges.remove(name);
  870. return;
  871. }
  872. if (name == null) {
  873. name = createBuiltInName(XSSFName.BUILTIN_PRINT_TITLE, sheetIndex);
  874. namedRanges.add(name);
  875. }
  876. String reference = getReferenceBuiltInRecord(name.getSheetName(), startColumn, endColumn, startRow, endRow);
  877. name.setRefersToFormula(reference);
  878. XSSFPrintSetup printSetup = sheet.getPrintSetup();
  879. printSetup.setValidSettings(false);
  880. }
  881. private static String getReferenceBuiltInRecord(String sheetName, int startC, int endC, int startR, int endR) {
  882. //windows excel example for built-in title: 'second sheet'!$E:$F,'second sheet'!$2:$3
  883. CellReference colRef = new CellReference(sheetName, 0, startC, true, true);
  884. CellReference colRef2 = new CellReference(sheetName, 0, endC, true, true);
  885. String escapedName = SheetNameFormatter.format(sheetName);
  886. String c;
  887. if(startC == -1 && endC == -1) c= "";
  888. else c = escapedName + "!$" + colRef.getCellRefParts()[2] + ":$" + colRef2.getCellRefParts()[2];
  889. CellReference rowRef = new CellReference(sheetName, startR, 0, true, true);
  890. CellReference rowRef2 = new CellReference(sheetName, endR, 0, true, true);
  891. String r = "";
  892. if(startR == -1 && endR == -1) r = "";
  893. else {
  894. if (!rowRef.getCellRefParts()[1].equals("0") && !rowRef2.getCellRefParts()[1].equals("0")) {
  895. r = escapedName + "!$" + rowRef.getCellRefParts()[1] + ":$" + rowRef2.getCellRefParts()[1];
  896. }
  897. }
  898. StringBuffer rng = new StringBuffer();
  899. rng.append(c);
  900. if(rng.length() > 0 && r.length() > 0) rng.append(',');
  901. rng.append(r);
  902. return rng.toString();
  903. }
  904. private static String getReferencePrintArea(String sheetName, int startC, int endC, int startR, int endR) {
  905. //windows excel example: Sheet1!$C$3:$E$4
  906. CellReference colRef = new CellReference(sheetName, startR, startC, true, true);
  907. CellReference colRef2 = new CellReference(sheetName, endR, endC, true, true);
  908. return "$" + colRef.getCellRefParts()[2] + "$" + colRef.getCellRefParts()[1] + ":$" + colRef2.getCellRefParts()[2] + "$" + colRef2.getCellRefParts()[1];
  909. }
  910. private XSSFName getBuiltInName(String builtInCode, int sheetNumber) {
  911. for (XSSFName name : namedRanges) {
  912. if (name.getNameName().equalsIgnoreCase(builtInCode) && name.getSheetIndex() == sheetNumber) {
  913. return name;
  914. }
  915. }
  916. return null;
  917. }
  918. /**
  919. * Generates a NameRecord to represent a built-in region
  920. *
  921. * @return a new NameRecord
  922. * @throws IllegalArgumentException if sheetNumber is invalid
  923. * @throws POIXMLException if such a name already exists in the workbook
  924. */
  925. private XSSFName createBuiltInName(String builtInName, int sheetNumber) {
  926. validateSheetIndex(sheetNumber);
  927. CTDefinedNames names = workbook.getDefinedNames() == null ? workbook.addNewDefinedNames() : workbook.getDefinedNames();
  928. CTDefinedName nameRecord = names.addNewDefinedName();
  929. nameRecord.setName(builtInName);
  930. nameRecord.setLocalSheetId(sheetNumber);
  931. XSSFName name = new XSSFName(nameRecord, this);
  932. for (XSSFName nr : namedRanges) {
  933. if (nr.equals(name))
  934. throw new POIXMLException("Builtin (" + builtInName
  935. + ") already exists for sheet (" + sheetNumber + ")");
  936. }
  937. return name;
  938. }
  939. /**
  940. * We only set one sheet as selected for compatibility with HSSF.
  941. */
  942. public void setSelectedTab(int index) {
  943. for (int i = 0 ; i < sheets.size() ; ++i) {
  944. XSSFSheet sheet = sheets.get(i);
  945. sheet.setSelected(i == index);
  946. }
  947. }
  948. /**
  949. * Set the sheet name.
  950. * Will throw IllegalArgumentException if the name is greater than 31 chars
  951. * or contains /\?*[]
  952. *
  953. * @param sheet number (0 based)
  954. * @see #validateSheetName(String)
  955. */
  956. public void setSheetName(int sheet, String name) {
  957. validateSheetIndex(sheet);
  958. validateSheetName(name);
  959. if (containsSheet(name, sheet ))
  960. throw new IllegalArgumentException( "The workbook already contains a sheet of this name" );
  961. workbook.getSheets().getSheetArray(sheet).setName(name);
  962. }
  963. /**
  964. * sets the order of appearance for a given sheet.
  965. *
  966. * @param sheetname the name of the sheet to reorder
  967. * @param pos the position that we want to insert the sheet into (0 based)
  968. */
  969. public void setSheetOrder(String sheetname, int pos) {
  970. int idx = getSheetIndex(sheetname);
  971. sheets.add(pos, sheets.remove(idx));
  972. // Reorder CTSheets
  973. CTSheets ct = workbook.getSheets();
  974. XmlObject cts = ct.getSheetArray(idx).copy();
  975. workbook.getSheets().removeSheet(idx);
  976. CTSheet newcts = ct.insertNewSheet(pos);
  977. newcts.set(cts);
  978. //notify sheets
  979. for(int i=0; i < sheets.size(); i++) {
  980. sheets.get(i).sheet = ct.getSheetArray(i);
  981. }
  982. }
  983. /**
  984. * marshal named ranges from the {@link #namedRanges} collection to the underlying CTWorkbook bean
  985. */
  986. private void saveNamedRanges(){
  987. // Named ranges
  988. if(namedRanges.size() > 0) {
  989. CTDefinedNames names = CTDefinedNames.Factory.newInstance();
  990. CTDefinedName[] nr = new CTDefinedName[namedRanges.size()];
  991. int i = 0;
  992. for(XSSFName name : namedRanges) {
  993. nr[i] = name.getCTName();
  994. i++;
  995. }
  996. names.setDefinedNameArray(nr);
  997. workbook.setDefinedNames(names);
  998. } else {
  999. if(workbook.isSetDefinedNames()) {
  1000. workbook.unsetDefinedNames();
  1001. }
  1002. }
  1003. }
  1004. private void saveCalculationChain(){
  1005. if(calcChain != null){
  1006. int count = calcChain.getCTCalcChain().getCArray().length;
  1007. if(count == 0){
  1008. removeRelation(calcChain);
  1009. calcChain = null;
  1010. }
  1011. }
  1012. }
  1013. @Override
  1014. protected void commit() throws IOException {
  1015. saveNamedRanges();
  1016. saveCalculationChain();
  1017. XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
  1018. xmlOptions.setSaveSyntheticDocumentElement(new QName(CTWorkbook.type.getName().getNamespaceURI(), "workbook"));
  1019. Map<String, String> map = new HashMap<String, String>();
  1020. map.put(STRelationshipId.type.getName().getNamespaceURI(), "r");
  1021. xmlOptions.setSaveSuggestedPrefixes(map);
  1022. PackagePart part = getPackagePart();
  1023. OutputStream out = part.getOutputStream();
  1024. workbook.save(out, xmlOptions);
  1025. out.close();
  1026. }
  1027. /**
  1028. * Returns SharedStringsTable - tha cache of string for this workbook
  1029. *
  1030. * @return the shared string table
  1031. */
  1032. public SharedStringsTable getSharedStringSource() {
  1033. return this.sharedStringSource;
  1034. }
  1035. /**
  1036. * Return a object representing a collection of shared objects used for styling content,
  1037. * e.g. fonts, cell styles, colors, etc.
  1038. */
  1039. public StylesTable getStylesSource() {
  1040. return this.stylesSource;
  1041. }
  1042. /**
  1043. * Returns an object that handles instantiating concrete
  1044. * classes of the various instances for XSSF.
  1045. */
  1046. public XSSFCreationHelper getCreationHelper() {
  1047. return new XSSFCreationHelper(this);
  1048. }
  1049. /**
  1050. * Determines whether a workbook contains the provided sheet name.
  1051. *
  1052. * @param name the name to test (case insensitive match)
  1053. * @param excludeSheetIdx the sheet to exclude from the check or -1 to include all sheets in the check.
  1054. * @return true if the sheet contains the name, false otherwise.
  1055. */
  1056. private boolean containsSheet(String name, int excludeSheetIdx) {
  1057. CTSheet[] ctSheetArray = workbook.getSheets().getSheetArray();
  1058. for (int i = 0; i < ctSheetArray.length; i++) {
  1059. if (excludeSheetIdx != i && name.equalsIgnoreCase(ctSheetArray[i].getName()))
  1060. return true;
  1061. }
  1062. return false;
  1063. }
  1064. /**
  1065. * Validates sheet name.
  1066. *
  1067. * <p>
  1068. * The character count <tt>MUST</tt> be greater than or equal to 1 and less than or equal to 31.
  1069. * The string MUST NOT contain the any of the following characters:
  1070. * <ul>
  1071. * <li> 0x0000 </li>
  1072. * <li> 0x0003 </li>
  1073. * <li> colon (:) </li>
  1074. * <li> backslash (\) </li>
  1075. * <li> asterisk (*) </li>
  1076. * <li> question mark (?) </li>
  1077. * <li> forward slash (/) </li>
  1078. * <li> opening square bracket ([) </li>
  1079. * <li> closing square bracket (]) </li>
  1080. * </ul>
  1081. * The string MUST NOT begin or end with the single quote (') character.
  1082. * </p>
  1083. *
  1084. * @param sheetName the name to validate
  1085. */
  1086. private static void validateSheetName(String sheetName) {
  1087. if (sheetName == null) {
  1088. throw new IllegalArgumentException("sheetName must not be null");
  1089. }
  1090. int len = sheetName.length();
  1091. if (len < 1 || len > 31) {
  1092. throw new IllegalArgumentException("sheetName '" + sheetName
  1093. + "' is invalid - must be 1-30 characters long");
  1094. }
  1095. for (int i=0; i<len; i++) {
  1096. char ch = sheetName.charAt(i);
  1097. switch (ch) {
  1098. case '/':
  1099. case '\\':
  1100. case '?':
  1101. case '*':
  1102. case ']':
  1103. case '[':
  1104. break;
  1105. default:
  1106. // all other chars OK
  1107. continue;
  1108. }
  1109. throw new IllegalArgumentException("Invalid char (" + ch
  1110. + ") found at index (" + i + ") in sheet name '" + sheetName + "'");
  1111. }
  1112. }
  1113. /**
  1114. * Gets a boolean value that indicates whether the date systems used in the workbook starts in 1904.
  1115. * <p>
  1116. * The default value is false, meaning that the workbook uses the 1900 date system,
  1117. * where 1/1/1900 is the first day in the system..
  1118. * </p>
  1119. * @return true if the date systems used in the workbook starts in 1904
  1120. */
  1121. protected boolean isDate1904(){
  1122. CTWorkbookPr workbookPr = workbook.getWorkbookPr();
  1123. return workbookPr != null && workbookPr.getDate1904();
  1124. }
  1125. /**
  1126. * Get the document's embedded files.
  1127. */
  1128. public List<PackagePart> getAllEmbedds() throws OpenXML4JException {
  1129. List<PackagePart> embedds = new LinkedList<PackagePart>();
  1130. for(XSSFSheet sheet : sheets){
  1131. // Get the embeddings for the workbook
  1132. for(PackageRelationship rel : sheet.getPackagePart().getRelationshipsByType(XSSFRelation.OLEEMBEDDINGS.getRelation()))
  1133. embedds.add(getTargetPart(rel));
  1134. for(PackageRelationship rel : sheet.getPackagePart().getRelationshipsByType(XSSFRelation.PACKEMBEDDINGS.getRelation()))
  1135. embedds.add(getTargetPart(rel));
  1136. }
  1137. return embedds;
  1138. }
  1139. public boolean isHidden() {
  1140. throw new RuntimeException("Not implemented yet");
  1141. }
  1142. public void setHidden(boolean hiddenFlag) {
  1143. throw new RuntimeException("Not implemented yet");
  1144. }
  1145. public boolean isSheetHidden(int sheetIx) {
  1146. validateSheetIndex(sheetIx);
  1147. CTSheet ctSheet = sheets.get(sheetIx).sheet;
  1148. return ctSheet.getState() == STSheetState.HIDDEN;
  1149. }
  1150. public boolean isSheetVeryHidden(int sheetIx) {
  1151. validateSheetIndex(sheetIx);
  1152. CTSheet ctSheet = sheets.get(sheetIx).sheet;
  1153. return ctSheet.getState() == STSheetState.VERY_HIDDEN;
  1154. }
  1155. public void setSheetHidden(int sheetIx, boolean hidden) {
  1156. validateSheetIndex(sheetIx);
  1157. CTSheet ctSheet = sheets.get(sheetIx).sheet;
  1158. ctSheet.setState(hidden ? STSheetState.HIDDEN : STSheetState.VISIBLE);
  1159. }
  1160. public void setSheetHidden(int sheetIx, int hidden) {
  1161. validateSheetIndex(sheetIx);
  1162. CTSheet ctSheet = sheets.get(sheetIx).sheet;
  1163. ctSheet.setState(STSheetState.Enum.forInt(hidden));
  1164. }
  1165. /**
  1166. * Fired when a formula is deleted from this workbook,
  1167. * for example when calling cell.setCellFormula(null)
  1168. *
  1169. * @see XSSFCell#setCellFormula(String)
  1170. */
  1171. protected void onDeleteFormula(XSSFCell cell){
  1172. if(calcChain != null) {
  1173. int sheetId = (int)cell.getSheet().sheet.getSheetId();
  1174. calcChain.removeItem(sheetId, cell.getReference());
  1175. }
  1176. }
  1177. /**
  1178. * Return the CalculationChain object for this workbook
  1179. * <p>
  1180. * The calculation chain object specifies the order in which the cells in a workbook were last calculated
  1181. * </p>
  1182. *
  1183. * @return the <code>CalculationChain</code> object or <code>null</code> if not defined
  1184. */
  1185. public CalculationChain getCalculationChain(){
  1186. return calcChain;
  1187. }
  1188. /**
  1189. *
  1190. * @return a collection of custom XML mappings defined in this workbook
  1191. */
  1192. public Collection<XSSFMap> getCustomXMLMappings(){
  1193. return mapInfo == null ? new ArrayList<XSSFMap>() : mapInfo.getAllXSSFMaps();
  1194. }
  1195. /**
  1196. *
  1197. * @return the helper class used to query the custom XML mapping defined in this workbook
  1198. */
  1199. public MapInfo getMapInfo(){
  1200. return mapInfo;
  1201. }
  1202. }