Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

XSSFWorkbook.java 52KB

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