Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

XSSFWorkbook.java 57KB

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