You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

StylesTable.java 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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.model;
  16. import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.io.OutputStream;
  20. import java.util.ArrayList;
  21. import java.util.Arrays;
  22. import java.util.Collections;
  23. import java.util.HashMap;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Map.Entry;
  27. import java.util.Set;
  28. import java.util.SortedMap;
  29. import java.util.TreeMap;
  30. import org.apache.poi.POIXMLDocumentPart;
  31. import org.apache.poi.openxml4j.opc.PackagePart;
  32. import org.apache.poi.ss.SpreadsheetVersion;
  33. import org.apache.poi.ss.usermodel.BuiltinFormats;
  34. import org.apache.poi.ss.usermodel.FontFamily;
  35. import org.apache.poi.ss.usermodel.FontScheme;
  36. import org.apache.poi.ss.usermodel.TableStyle;
  37. import org.apache.poi.util.Internal;
  38. import org.apache.poi.xssf.usermodel.CustomIndexedColorMap;
  39. import org.apache.poi.xssf.usermodel.DefaultIndexedColorMap;
  40. import org.apache.poi.xssf.usermodel.IndexedColorMap;
  41. import org.apache.poi.xssf.usermodel.XSSFBuiltinTableStyle;
  42. import org.apache.poi.xssf.usermodel.XSSFCellStyle;
  43. import org.apache.poi.xssf.usermodel.XSSFFactory;
  44. import org.apache.poi.xssf.usermodel.XSSFFont;
  45. import org.apache.poi.xssf.usermodel.XSSFRelation;
  46. import org.apache.poi.xssf.usermodel.XSSFTableStyle;
  47. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  48. import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder;
  49. import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill;
  50. import org.apache.xmlbeans.XmlException;
  51. import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
  52. /**
  53. * Table of styles shared across all sheets in a workbook.
  54. */
  55. public class StylesTable extends POIXMLDocumentPart {
  56. private final SortedMap<Short, String> numberFormats = new TreeMap<Short,String>();
  57. private final List<XSSFFont> fonts = new ArrayList<XSSFFont>();
  58. private final List<XSSFCellFill> fills = new ArrayList<XSSFCellFill>();
  59. private final List<XSSFCellBorder> borders = new ArrayList<XSSFCellBorder>();
  60. private final List<CTXf> styleXfs = new ArrayList<CTXf>();
  61. private final List<CTXf> xfs = new ArrayList<CTXf>();
  62. private final List<CTDxf> dxfs = new ArrayList<CTDxf>();
  63. private final Map<String, TableStyle> tableStyles = new HashMap<String, TableStyle>();
  64. private IndexedColorMap indexedColors = new DefaultIndexedColorMap();
  65. /**
  66. * The first style id available for use as a custom style
  67. */
  68. public static final int FIRST_CUSTOM_STYLE_ID = BuiltinFormats.FIRST_USER_DEFINED_FORMAT_INDEX + 1;
  69. // Is this right? Number formats (XSSFDataFormat) and cell styles (XSSFCellStyle) are different. What's up with the plus 1?
  70. private static final int MAXIMUM_STYLE_ID = SpreadsheetVersion.EXCEL2007.getMaxCellStyles();
  71. private static final short FIRST_USER_DEFINED_NUMBER_FORMAT_ID = BuiltinFormats.FIRST_USER_DEFINED_FORMAT_INDEX;
  72. /**
  73. * Depending on the version of Excel, the maximum number of number formats in a workbook is between 200 and 250
  74. * See https://support.office.com/en-us/article/excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3
  75. * POI defaults this limit to 250, but can be increased or decreased on a per-StylesTable basis with
  76. * {@link #setMaxNumberOfDataFormats(int)} if needed.
  77. */
  78. private int MAXIMUM_NUMBER_OF_DATA_FORMATS = 250;
  79. /**
  80. * Changes the maximum number of data formats that may be in a style table
  81. *
  82. * @param num the upper limit on number of data formats in the styles table when adding new data formats
  83. * @throws IllegalArgumentException if <code>num</code> < 0
  84. * @throws IllegalStateException if <code>num</code> < current number of data formats in the style table.
  85. * Data formats must be explicitly removed before the limit can be decreased.
  86. */
  87. public void setMaxNumberOfDataFormats(int num) {
  88. if (num < getNumDataFormats()) {
  89. if (num < 0) {
  90. throw new IllegalArgumentException("Maximum Number of Data Formats must be greater than or equal to 0");
  91. } else {
  92. throw new IllegalStateException("Cannot set the maximum number of data formats less than the current quantity." +
  93. "Data formats must be explicitly removed (via StylesTable.removeNumberFormat) before the limit can be decreased.");
  94. }
  95. }
  96. MAXIMUM_NUMBER_OF_DATA_FORMATS = num;
  97. }
  98. /**
  99. * Get the upper limit on the number of data formats that has been set for the style table.
  100. * To get the current number of data formats in use, use {@link #getNumDataFormats()}.
  101. *
  102. * @return the maximum number of data formats allowed in the workbook
  103. */
  104. public int getMaxNumberOfDataFormats() {
  105. return MAXIMUM_NUMBER_OF_DATA_FORMATS;
  106. }
  107. private StyleSheetDocument doc;
  108. private XSSFWorkbook workbook;
  109. private ThemesTable theme;
  110. /**
  111. * Create a new, empty StylesTable
  112. */
  113. public StylesTable() {
  114. super();
  115. doc = StyleSheetDocument.Factory.newInstance();
  116. doc.addNewStyleSheet();
  117. // Initialization required in order to make the document readable by MSExcel
  118. initialize();
  119. }
  120. /**
  121. * @since POI 3.14-Beta1
  122. */
  123. public StylesTable(PackagePart part) throws IOException {
  124. super(part);
  125. readFrom(part.getInputStream());
  126. }
  127. public void setWorkbook(XSSFWorkbook wb) {
  128. this.workbook = wb;
  129. }
  130. /**
  131. * Get the current Workbook's theme table, or null if the
  132. * Workbook lacks any themes.
  133. * <p>Use {@link #ensureThemesTable()} to have a themes table
  134. * created if needed
  135. */
  136. public ThemesTable getTheme() {
  137. return theme;
  138. }
  139. public void setTheme(ThemesTable theme) {
  140. this.theme = theme;
  141. if (theme != null) theme.setColorMap(getIndexedColors());
  142. // Pass the themes table along to things which need to
  143. // know about it, but have already been created by now
  144. for(XSSFFont font : fonts) {
  145. font.setThemesTable(theme);
  146. }
  147. for(XSSFCellBorder border : borders) {
  148. border.setThemesTable(theme);
  149. }
  150. }
  151. /**
  152. * If there isn't currently a {@link ThemesTable} for the
  153. * current Workbook, then creates one and sets it up.
  154. * After this, calls to {@link #getTheme()} won't give null
  155. */
  156. public void ensureThemesTable() {
  157. if (theme != null) return;
  158. setTheme((ThemesTable)workbook.createRelationship(XSSFRelation.THEME, XSSFFactory.getInstance()));
  159. }
  160. /**
  161. * Read this shared styles table from an XML file.
  162. *
  163. * @param is The input stream containing the XML document.
  164. * @throws IOException if an error occurs while reading.
  165. */
  166. public void readFrom(InputStream is) throws IOException {
  167. try {
  168. doc = StyleSheetDocument.Factory.parse(is, DEFAULT_XML_OPTIONS);
  169. CTStylesheet styleSheet = doc.getStyleSheet();
  170. // Grab all the different bits we care about
  171. // keep this first, as some constructors below want it
  172. IndexedColorMap customColors = CustomIndexedColorMap.fromColors(styleSheet.getColors());
  173. if (customColors != null) indexedColors = customColors;
  174. CTNumFmts ctfmts = styleSheet.getNumFmts();
  175. if( ctfmts != null){
  176. for (CTNumFmt nfmt : ctfmts.getNumFmtArray()) {
  177. short formatId = (short)nfmt.getNumFmtId();
  178. numberFormats.put(formatId, nfmt.getFormatCode());
  179. }
  180. }
  181. CTFonts ctfonts = styleSheet.getFonts();
  182. if(ctfonts != null){
  183. int idx = 0;
  184. for (CTFont font : ctfonts.getFontArray()) {
  185. // Create the font and save it. Themes Table supplied later
  186. XSSFFont f = new XSSFFont(font, idx, indexedColors);
  187. fonts.add(f);
  188. idx++;
  189. }
  190. }
  191. CTFills ctfills = styleSheet.getFills();
  192. if(ctfills != null){
  193. for (CTFill fill : ctfills.getFillArray()) {
  194. fills.add(new XSSFCellFill(fill, indexedColors));
  195. }
  196. }
  197. CTBorders ctborders = styleSheet.getBorders();
  198. if(ctborders != null) {
  199. for (CTBorder border : ctborders.getBorderArray()) {
  200. borders.add(new XSSFCellBorder(border, indexedColors));
  201. }
  202. }
  203. CTCellXfs cellXfs = styleSheet.getCellXfs();
  204. if(cellXfs != null) xfs.addAll(Arrays.asList(cellXfs.getXfArray()));
  205. CTCellStyleXfs cellStyleXfs = styleSheet.getCellStyleXfs();
  206. if(cellStyleXfs != null) styleXfs.addAll(Arrays.asList(cellStyleXfs.getXfArray()));
  207. CTDxfs styleDxfs = styleSheet.getDxfs();
  208. if(styleDxfs != null) dxfs.addAll(Arrays.asList(styleDxfs.getDxfArray()));
  209. CTTableStyles ctTableStyles = styleSheet.getTableStyles();
  210. if (ctTableStyles != null) {
  211. int idx = 0;
  212. for (CTTableStyle style : Arrays.asList(ctTableStyles.getTableStyleArray())) {
  213. tableStyles.put(style.getName(), new XSSFTableStyle(idx, styleDxfs, style, indexedColors));
  214. idx++;
  215. }
  216. }
  217. } catch (XmlException e) {
  218. throw new IOException(e.getLocalizedMessage());
  219. }
  220. }
  221. // ===========================================================
  222. // Start of style related getters and setters
  223. // ===========================================================
  224. /**
  225. * Get number format string given its id
  226. *
  227. * @param fmtId number format id
  228. * @return number format code
  229. */
  230. public String getNumberFormatAt(short fmtId) {
  231. return numberFormats.get(fmtId);
  232. }
  233. private short getNumberFormatId(String fmt) {
  234. // Find the key, and return that
  235. for (Entry<Short,String> numFmt : numberFormats.entrySet()) {
  236. if(numFmt.getValue().equals(fmt)) {
  237. return numFmt.getKey();
  238. }
  239. }
  240. throw new IllegalStateException("Number format not in style table: " + fmt);
  241. }
  242. /**
  243. * Puts <code>fmt</code> in the numberFormats map if the format is not
  244. * already in the the number format style table.
  245. * Does nothing if <code>fmt</code> is already in number format style table.
  246. *
  247. * @param fmt the number format to add to number format style table
  248. * @return the index of <code>fmt</code> in the number format style table
  249. * @throws IllegalStateException if adding the number format to the styles table
  250. * would exceed the {@link #MAXIMUM_NUMBER_OF_DATA_FORMATS} allowed.
  251. */
  252. public int putNumberFormat(String fmt) {
  253. // Check if number format already exists
  254. if (numberFormats.containsValue(fmt)) {
  255. try {
  256. return getNumberFormatId(fmt);
  257. } catch (final IllegalStateException e) {
  258. throw new IllegalStateException("Found the format, but couldn't figure out where - should never happen!");
  259. }
  260. }
  261. if (numberFormats.size() >= MAXIMUM_NUMBER_OF_DATA_FORMATS) {
  262. throw new IllegalStateException("The maximum number of Data Formats was exceeded. " +
  263. "You can define up to " + MAXIMUM_NUMBER_OF_DATA_FORMATS + " formats in a .xlsx Workbook.");
  264. }
  265. // Find a spare key, and add that
  266. final short formatIndex;
  267. if (numberFormats.isEmpty()) {
  268. formatIndex = FIRST_USER_DEFINED_NUMBER_FORMAT_ID;
  269. }
  270. else {
  271. // get next-available numberFormat index.
  272. // Assumption: gaps in number format ids are acceptable
  273. // to catch arithmetic overflow, nextKey's data type
  274. // must match numberFormat's key data type
  275. short nextKey = (short) (numberFormats.lastKey() + 1);
  276. if (nextKey < 0) {
  277. throw new IllegalStateException(
  278. "Cowardly avoiding creating a number format with a negative id." +
  279. "This is probably due to arithmetic overflow.");
  280. }
  281. formatIndex = (short) Math.max(nextKey, FIRST_USER_DEFINED_NUMBER_FORMAT_ID);
  282. }
  283. numberFormats.put(formatIndex, fmt);
  284. return formatIndex;
  285. }
  286. /**
  287. * Add a number format with a specific ID into the numberFormats map.
  288. * If a format with the same ID already exists, overwrite the format code
  289. * with <code>fmt</code>
  290. * This may be used to override built-in number formats.
  291. *
  292. * @param index the number format ID
  293. * @param fmt the number format code
  294. */
  295. public void putNumberFormat(short index, String fmt) {
  296. numberFormats.put(index, fmt);
  297. }
  298. /**
  299. * Remove a number format from the style table if it exists.
  300. * All cell styles with this number format will be modified to use the default number format.
  301. *
  302. * @param index the number format id to remove
  303. * @return true if the number format was removed
  304. */
  305. public boolean removeNumberFormat(short index) {
  306. String fmt = numberFormats.remove(index);
  307. boolean removed = (fmt != null);
  308. if (removed) {
  309. for (final CTXf style : xfs) {
  310. if (style.isSetNumFmtId() && style.getNumFmtId() == index) {
  311. style.unsetApplyNumberFormat();
  312. style.unsetNumFmtId();
  313. }
  314. }
  315. }
  316. return removed;
  317. }
  318. /**
  319. * Remove a number format from the style table if it exists
  320. * All cell styles with this number format will be modified to use the default number format
  321. *
  322. * @param fmt the number format to remove
  323. * @return true if the number format was removed
  324. */
  325. public boolean removeNumberFormat(String fmt) {
  326. short id = getNumberFormatId(fmt);
  327. return removeNumberFormat(id);
  328. }
  329. public XSSFFont getFontAt(int idx) {
  330. return fonts.get(idx);
  331. }
  332. /**
  333. * Records the given font in the font table.
  334. * Will re-use an existing font index if this
  335. * font matches another, EXCEPT if forced
  336. * registration is requested.
  337. * This allows people to create several fonts
  338. * then customise them later.
  339. * Note - End Users probably want to call
  340. * {@link XSSFFont#registerTo(StylesTable)}
  341. */
  342. public int putFont(XSSFFont font, boolean forceRegistration) {
  343. int idx = -1;
  344. if(!forceRegistration) {
  345. idx = fonts.indexOf(font);
  346. }
  347. if (idx != -1) {
  348. return idx;
  349. }
  350. idx = fonts.size();
  351. fonts.add(font);
  352. return idx;
  353. }
  354. public int putFont(XSSFFont font) {
  355. return putFont(font, false);
  356. }
  357. /**
  358. *
  359. * @param idx style index
  360. * @return XSSFCellStyle or null if idx is out of bounds for xfs array
  361. */
  362. public XSSFCellStyle getStyleAt(int idx) {
  363. int styleXfId = 0;
  364. if (idx < 0 || idx >= xfs.size()) {
  365. //BUG-60343
  366. return null;
  367. }
  368. // 0 is the empty default
  369. if(xfs.get(idx).getXfId() > 0) {
  370. styleXfId = (int) xfs.get(idx).getXfId();
  371. }
  372. return new XSSFCellStyle(idx, styleXfId, this, theme);
  373. }
  374. public int putStyle(XSSFCellStyle style) {
  375. CTXf mainXF = style.getCoreXf();
  376. if(! xfs.contains(mainXF)) {
  377. xfs.add(mainXF);
  378. }
  379. return xfs.indexOf(mainXF);
  380. }
  381. public XSSFCellBorder getBorderAt(int idx) {
  382. return borders.get(idx);
  383. }
  384. /**
  385. * Adds a border to the border style table if it isn't already in the style table
  386. * Does nothing if border is already in borders style table
  387. *
  388. * @param border border to add
  389. * @return the index of the added border
  390. */
  391. public int putBorder(XSSFCellBorder border) {
  392. int idx = borders.indexOf(border);
  393. if (idx != -1) {
  394. return idx;
  395. }
  396. borders.add(border);
  397. border.setThemesTable(theme);
  398. return borders.size() - 1;
  399. }
  400. public XSSFCellFill getFillAt(int idx) {
  401. return fills.get(idx);
  402. }
  403. public List<XSSFCellBorder> getBorders(){
  404. return Collections.unmodifiableList(borders);
  405. }
  406. public List<XSSFCellFill> getFills(){
  407. return Collections.unmodifiableList(fills);
  408. }
  409. public List<XSSFFont> getFonts(){
  410. return Collections.unmodifiableList(fonts);
  411. }
  412. public Map<Short, String> getNumberFormats(){
  413. return Collections.unmodifiableMap(numberFormats);
  414. }
  415. /**
  416. * Adds a fill to the fill style table if it isn't already in the style table
  417. * Does nothing if fill is already in fill style table
  418. *
  419. * @param fill fill to add
  420. * @return the index of the added fill
  421. */
  422. public int putFill(XSSFCellFill fill) {
  423. int idx = fills.indexOf(fill);
  424. if (idx != -1) {
  425. return idx;
  426. }
  427. fills.add(fill);
  428. return fills.size() - 1;
  429. }
  430. @Internal
  431. public CTXf getCellXfAt(int idx) {
  432. return xfs.get(idx);
  433. }
  434. /**
  435. * Adds a cell to the styles table.
  436. * Does not check for duplicates.
  437. *
  438. * @param cellXf the cell to add to the styles table
  439. * @return the added cell ID in the style table
  440. */
  441. @Internal
  442. public int putCellXf(CTXf cellXf) {
  443. xfs.add(cellXf);
  444. return xfs.size();
  445. }
  446. @Internal
  447. public void replaceCellXfAt(int idx, CTXf cellXf) {
  448. xfs.set(idx, cellXf);
  449. }
  450. @Internal
  451. public CTXf getCellStyleXfAt(int idx) {
  452. try {
  453. return styleXfs.get(idx);
  454. }
  455. catch (final IndexOutOfBoundsException e) {
  456. return null;
  457. }
  458. }
  459. /**
  460. * Adds a cell style to the styles table.
  461. * Does not check for duplicates.
  462. *
  463. * @param cellStyleXf the cell style to add to the styles table
  464. * @return the cell style ID in the style table
  465. */
  466. @Internal
  467. public int putCellStyleXf(CTXf cellStyleXf) {
  468. styleXfs.add(cellStyleXf);
  469. // TODO: check for duplicate
  470. return styleXfs.size();
  471. }
  472. @Internal
  473. protected void replaceCellStyleXfAt(int idx, CTXf cellStyleXf) {
  474. styleXfs.set(idx, cellStyleXf);
  475. }
  476. /**
  477. * get the size of cell styles
  478. */
  479. public int getNumCellStyles(){
  480. // Each cell style has a unique xfs entry
  481. // Several might share the same styleXfs entry
  482. return xfs.size();
  483. }
  484. /**
  485. * @return number of data formats in the styles table
  486. */
  487. public int getNumDataFormats() {
  488. return numberFormats.size();
  489. }
  490. /**
  491. * For unit testing only
  492. * @deprecated POI 3.14 beta 2. Use {@link #getNumDataFormats()} instead.
  493. */
  494. @Internal
  495. public int _getNumberFormatSize() {
  496. return getNumDataFormats();
  497. }
  498. /**
  499. * For unit testing only
  500. */
  501. @Internal
  502. /*package*/ int _getXfsSize() {
  503. return xfs.size();
  504. }
  505. /**
  506. * For unit testing only
  507. */
  508. @Internal
  509. public int _getStyleXfsSize() {
  510. return styleXfs.size();
  511. }
  512. /**
  513. * For unit testing only!
  514. */
  515. @Internal
  516. public CTStylesheet getCTStylesheet() {
  517. return doc.getStyleSheet();
  518. }
  519. @Internal
  520. public int _getDXfsSize() {
  521. return dxfs.size();
  522. }
  523. /**
  524. * Write this table out as XML.
  525. *
  526. * @param out The stream to write to.
  527. * @throws IOException if an error occurs while writing.
  528. */
  529. public void writeTo(OutputStream out) throws IOException {
  530. // Work on the current one
  531. // Need to do this, as we don't handle
  532. // all the possible entries yet
  533. CTStylesheet styleSheet = doc.getStyleSheet();
  534. // Formats
  535. CTNumFmts formats = CTNumFmts.Factory.newInstance();
  536. formats.setCount(numberFormats.size());
  537. for (final Entry<Short, String> entry : numberFormats.entrySet()) {
  538. CTNumFmt ctFmt = formats.addNewNumFmt();
  539. ctFmt.setNumFmtId(entry.getKey());
  540. ctFmt.setFormatCode(entry.getValue());
  541. }
  542. styleSheet.setNumFmts(formats);
  543. int idx;
  544. // Fonts
  545. CTFonts ctFonts = styleSheet.getFonts();
  546. if (ctFonts == null) {
  547. ctFonts = CTFonts.Factory.newInstance();
  548. }
  549. ctFonts.setCount(fonts.size());
  550. CTFont[] ctfnt = new CTFont[fonts.size()];
  551. idx = 0;
  552. for(XSSFFont f : fonts) ctfnt[idx++] = f.getCTFont();
  553. ctFonts.setFontArray(ctfnt);
  554. styleSheet.setFonts(ctFonts);
  555. // Fills
  556. CTFills ctFills = styleSheet.getFills();
  557. if (ctFills == null) {
  558. ctFills = CTFills.Factory.newInstance();
  559. }
  560. ctFills.setCount(fills.size());
  561. CTFill[] ctf = new CTFill[fills.size()];
  562. idx = 0;
  563. for(XSSFCellFill f : fills) ctf[idx++] = f.getCTFill();
  564. ctFills.setFillArray(ctf);
  565. styleSheet.setFills(ctFills);
  566. // Borders
  567. CTBorders ctBorders = styleSheet.getBorders();
  568. if (ctBorders == null) {
  569. ctBorders = CTBorders.Factory.newInstance();
  570. }
  571. ctBorders.setCount(borders.size());
  572. CTBorder[] ctb = new CTBorder[borders.size()];
  573. idx = 0;
  574. for(XSSFCellBorder b : borders) ctb[idx++] = b.getCTBorder();
  575. ctBorders.setBorderArray(ctb);
  576. styleSheet.setBorders(ctBorders);
  577. // Xfs
  578. if(xfs.size() > 0) {
  579. CTCellXfs ctXfs = styleSheet.getCellXfs();
  580. if (ctXfs == null) {
  581. ctXfs = CTCellXfs.Factory.newInstance();
  582. }
  583. ctXfs.setCount(xfs.size());
  584. ctXfs.setXfArray(
  585. xfs.toArray(new CTXf[xfs.size()])
  586. );
  587. styleSheet.setCellXfs(ctXfs);
  588. }
  589. // Style xfs
  590. if(styleXfs.size() > 0) {
  591. CTCellStyleXfs ctSXfs = styleSheet.getCellStyleXfs();
  592. if (ctSXfs == null) {
  593. ctSXfs = CTCellStyleXfs.Factory.newInstance();
  594. }
  595. ctSXfs.setCount(styleXfs.size());
  596. ctSXfs.setXfArray(
  597. styleXfs.toArray(new CTXf[styleXfs.size()])
  598. );
  599. styleSheet.setCellStyleXfs(ctSXfs);
  600. }
  601. // Style dxfs
  602. if(dxfs.size() > 0) {
  603. CTDxfs ctDxfs = styleSheet.getDxfs();
  604. if (ctDxfs == null) {
  605. ctDxfs = CTDxfs.Factory.newInstance();
  606. }
  607. ctDxfs.setCount(dxfs.size());
  608. ctDxfs.setDxfArray(dxfs.toArray(new CTDxf[dxfs.size()]));
  609. styleSheet.setDxfs(ctDxfs);
  610. }
  611. // Save
  612. doc.save(out, DEFAULT_XML_OPTIONS);
  613. }
  614. @Override
  615. protected void commit() throws IOException {
  616. PackagePart part = getPackagePart();
  617. OutputStream out = part.getOutputStream();
  618. writeTo(out);
  619. out.close();
  620. }
  621. private void initialize() {
  622. //CTFont ctFont = createDefaultFont();
  623. XSSFFont xssfFont = createDefaultFont();
  624. fonts.add(xssfFont);
  625. CTFill[] ctFill = createDefaultFills();
  626. fills.add(new XSSFCellFill(ctFill[0], indexedColors));
  627. fills.add(new XSSFCellFill(ctFill[1], indexedColors));
  628. CTBorder ctBorder = createDefaultBorder();
  629. borders.add(new XSSFCellBorder(ctBorder));
  630. CTXf styleXf = createDefaultXf();
  631. styleXfs.add(styleXf);
  632. CTXf xf = createDefaultXf();
  633. xf.setXfId(0);
  634. xfs.add(xf);
  635. }
  636. private static CTXf createDefaultXf() {
  637. CTXf ctXf = CTXf.Factory.newInstance();
  638. ctXf.setNumFmtId(0);
  639. ctXf.setFontId(0);
  640. ctXf.setFillId(0);
  641. ctXf.setBorderId(0);
  642. return ctXf;
  643. }
  644. private static CTBorder createDefaultBorder() {
  645. CTBorder ctBorder = CTBorder.Factory.newInstance();
  646. ctBorder.addNewBottom();
  647. ctBorder.addNewTop();
  648. ctBorder.addNewLeft();
  649. ctBorder.addNewRight();
  650. ctBorder.addNewDiagonal();
  651. return ctBorder;
  652. }
  653. private static CTFill[] createDefaultFills() {
  654. CTFill[] ctFill = new CTFill[]{CTFill.Factory.newInstance(),CTFill.Factory.newInstance()};
  655. ctFill[0].addNewPatternFill().setPatternType(STPatternType.NONE);
  656. ctFill[1].addNewPatternFill().setPatternType(STPatternType.DARK_GRAY);
  657. return ctFill;
  658. }
  659. private static XSSFFont createDefaultFont() {
  660. CTFont ctFont = CTFont.Factory.newInstance();
  661. XSSFFont xssfFont=new XSSFFont(ctFont, 0, null);
  662. xssfFont.setFontHeightInPoints(XSSFFont.DEFAULT_FONT_SIZE);
  663. xssfFont.setColor(XSSFFont.DEFAULT_FONT_COLOR);//setTheme
  664. xssfFont.setFontName(XSSFFont.DEFAULT_FONT_NAME);
  665. xssfFont.setFamily(FontFamily.SWISS);
  666. xssfFont.setScheme(FontScheme.MINOR);
  667. return xssfFont;
  668. }
  669. @Internal
  670. public CTDxf getDxfAt(int idx) {
  671. return dxfs.get(idx);
  672. }
  673. /**
  674. * Adds a Dxf to the style table
  675. * Does not check for duplicates.
  676. *
  677. * @param dxf the Dxf to add
  678. * @return added dxf ID in the style table
  679. */
  680. @Internal
  681. public int putDxf(CTDxf dxf) {
  682. this.dxfs.add(dxf);
  683. return this.dxfs.size();
  684. }
  685. /**
  686. * NOTE: this only returns explicitly defined styles
  687. * @param name of the table style
  688. * @return defined style, or null if not explicitly defined
  689. *
  690. * @since 3.17 beta 1
  691. */
  692. public TableStyle getExplicitTableStyle(String name) {
  693. return tableStyles.get(name);
  694. }
  695. /**
  696. * @return names of all explicitly defined table styles in the workbook
  697. * @since 3.17 beta 1
  698. */
  699. public Set<String> getExplicitTableStyleNames() {
  700. return tableStyles.keySet();
  701. }
  702. /**
  703. * @param name of the table style
  704. * @return defined style, either explicit or built-in, or null if not found
  705. *
  706. * @since 3.17 beta 1
  707. */
  708. public TableStyle getTableStyle(String name) {
  709. if (name == null) return null;
  710. try {
  711. return XSSFBuiltinTableStyle.valueOf(name).getStyle();
  712. } catch (IllegalArgumentException e) {
  713. return getExplicitTableStyle(name);
  714. }
  715. }
  716. /**
  717. * Create a cell style in this style table.
  718. * Note - End users probably want to call {@link XSSFWorkbook#createCellStyle()}
  719. * rather than working with the styles table directly.
  720. * @throws IllegalStateException if the maximum number of cell styles has been reached.
  721. */
  722. public XSSFCellStyle createCellStyle() {
  723. if (getNumCellStyles() > MAXIMUM_STYLE_ID) {
  724. throw new IllegalStateException("The maximum number of Cell Styles was exceeded. " +
  725. "You can define up to " + MAXIMUM_STYLE_ID + " style in a .xlsx Workbook");
  726. }
  727. int xfSize = styleXfs.size();
  728. CTXf xf = CTXf.Factory.newInstance();
  729. xf.setNumFmtId(0);
  730. xf.setFontId(0);
  731. xf.setFillId(0);
  732. xf.setBorderId(0);
  733. xf.setXfId(0);
  734. int indexXf = putCellXf(xf);
  735. return new XSSFCellStyle(indexXf - 1, xfSize - 1, this, theme);
  736. }
  737. /**
  738. * Finds a font that matches the one with the supplied attributes
  739. * @deprecated POI 3.15 beta 2. Use {@link #findFont(boolean, short, short, String, boolean, boolean, short, byte)} instead.
  740. */
  741. public XSSFFont findFont(short boldWeight, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) {
  742. for (XSSFFont font : fonts) {
  743. if ( (font.getBoldweight() == boldWeight)
  744. && font.getColor() == color
  745. && font.getFontHeight() == fontHeight
  746. && font.getFontName().equals(name)
  747. && font.getItalic() == italic
  748. && font.getStrikeout() == strikeout
  749. && font.getTypeOffset() == typeOffset
  750. && font.getUnderline() == underline)
  751. {
  752. return font;
  753. }
  754. }
  755. return null;
  756. }
  757. /**
  758. * Finds a font that matches the one with the supplied attributes
  759. */
  760. public XSSFFont findFont(boolean bold, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) {
  761. for (XSSFFont font : fonts) {
  762. if ( (font.getBold() == bold)
  763. && font.getColor() == color
  764. && font.getFontHeight() == fontHeight
  765. && font.getFontName().equals(name)
  766. && font.getItalic() == italic
  767. && font.getStrikeout() == strikeout
  768. && font.getTypeOffset() == typeOffset
  769. && font.getUnderline() == underline)
  770. {
  771. return font;
  772. }
  773. }
  774. return null;
  775. }
  776. /**
  777. * @return default or custom indexed color to RGB mapping
  778. */
  779. public IndexedColorMap getIndexedColors() {
  780. return indexedColors;
  781. }
  782. }