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.

XSSFPivotCacheDefinition.java 7.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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 static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.io.OutputStream;
  20. import java.util.Date;
  21. import javax.xml.namespace.QName;
  22. import org.apache.poi.ooxml.POIXMLDocumentPart;
  23. import org.apache.poi.openxml4j.opc.PackagePart;
  24. import org.apache.poi.ss.SpreadsheetVersion;
  25. import org.apache.poi.ss.usermodel.Name;
  26. import org.apache.poi.ss.usermodel.Row;
  27. import org.apache.poi.ss.usermodel.Sheet;
  28. import org.apache.poi.ss.usermodel.Workbook;
  29. import org.apache.poi.ss.util.AreaReference;
  30. import org.apache.poi.ss.util.CellReference;
  31. import org.apache.poi.util.Beta;
  32. import org.apache.poi.util.Internal;
  33. import org.apache.xmlbeans.XmlException;
  34. import org.apache.xmlbeans.XmlOptions;
  35. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCacheField;
  36. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCacheFields;
  37. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotCacheDefinition;
  38. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheetSource;
  39. public class XSSFPivotCacheDefinition extends POIXMLDocumentPart{
  40. private CTPivotCacheDefinition ctPivotCacheDefinition;
  41. @Beta
  42. public XSSFPivotCacheDefinition() {
  43. super();
  44. ctPivotCacheDefinition = CTPivotCacheDefinition.Factory.newInstance();
  45. createDefaultValues();
  46. }
  47. /**
  48. * Creates an XSSFPivotCacheDefintion representing the given package part and relationship.
  49. * Should only be called when reading in an existing file.
  50. *
  51. * @param part - The package part that holds xml data representing this pivot cache definition.
  52. *
  53. * @since POI 3.14-Beta1
  54. */
  55. @Beta
  56. protected XSSFPivotCacheDefinition(PackagePart part) throws IOException {
  57. super(part);
  58. try (InputStream stream = part.getInputStream()) {
  59. readFrom(stream);
  60. }
  61. }
  62. @Beta
  63. public void readFrom(InputStream is) throws IOException {
  64. try {
  65. XmlOptions options = new XmlOptions(DEFAULT_XML_OPTIONS);
  66. //Removing root element
  67. options.setLoadReplaceDocumentElement(null);
  68. ctPivotCacheDefinition = CTPivotCacheDefinition.Factory.parse(is, options);
  69. } catch (XmlException e) {
  70. throw new IOException(e.getLocalizedMessage(), e);
  71. }
  72. }
  73. @Beta
  74. @Internal
  75. public CTPivotCacheDefinition getCTPivotCacheDefinition() {
  76. return ctPivotCacheDefinition;
  77. }
  78. @Beta
  79. private void createDefaultValues() {
  80. ctPivotCacheDefinition.setCreatedVersion(XSSFPivotTable.CREATED_VERSION);
  81. ctPivotCacheDefinition.setMinRefreshableVersion(XSSFPivotTable.MIN_REFRESHABLE_VERSION);
  82. ctPivotCacheDefinition.setRefreshedVersion(XSSFPivotTable.UPDATED_VERSION);
  83. ctPivotCacheDefinition.setRefreshedBy("Apache POI");
  84. ctPivotCacheDefinition.setRefreshedDate(new Date().getTime());
  85. ctPivotCacheDefinition.setRefreshOnLoad(true);
  86. }
  87. @Beta
  88. @Override
  89. protected void commit() throws IOException {
  90. PackagePart part = getPackagePart();
  91. try (OutputStream out = part.getOutputStream()) {
  92. XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
  93. //Sets the pivotCacheDefinition tag
  94. xmlOptions.setSaveSyntheticDocumentElement(new QName(CTPivotCacheDefinition.type.getName().
  95. getNamespaceURI(), "pivotCacheDefinition"));
  96. ctPivotCacheDefinition.save(out, xmlOptions);
  97. }
  98. }
  99. /**
  100. * Find the 2D base data area for the pivot table, either from its direct reference or named table/range.
  101. * @return AreaReference representing the current area defined by the pivot table
  102. * @throws IllegalArgumentException if the ref attribute is not contiguous or the name attribute is not found.
  103. */
  104. @Beta
  105. public AreaReference getPivotArea(Workbook wb) throws IllegalArgumentException {
  106. final CTWorksheetSource wsSource = ctPivotCacheDefinition.getCacheSource().getWorksheetSource();
  107. final String ref = wsSource.getRef();
  108. final String name = wsSource.getName();
  109. if (ref == null && name == null) {
  110. throw new IllegalArgumentException("Pivot cache must reference an area, named range, or table.");
  111. }
  112. // this is the XML format, so tell the reference that.
  113. if (ref != null) {
  114. return new AreaReference(ref, SpreadsheetVersion.EXCEL2007);
  115. }
  116. assert (name != null);
  117. // named range or table?
  118. final Name range = wb.getName(name);
  119. if (range != null) {
  120. return new AreaReference(range.getRefersToFormula(), SpreadsheetVersion.EXCEL2007);
  121. }
  122. // not a named range, check for a table.
  123. // do this second, as tables are sheet-specific, but named ranges are not, and may not have a sheet name given.
  124. final XSSFSheet sheet = (XSSFSheet) wb.getSheet(wsSource.getSheet());
  125. for (XSSFTable table : sheet.getTables()) {
  126. // TODO: case-sensitive?
  127. if (name.equals(table.getName())) {
  128. return new AreaReference(table.getStartCellReference(), table.getEndCellReference(),
  129. SpreadsheetVersion.EXCEL2007);
  130. }
  131. }
  132. throw new IllegalArgumentException("Name '" + name + "' was not found.");
  133. }
  134. /**
  135. * Generates a cache field for each column in the reference area for the pivot table.
  136. * @param sheet The sheet where the data i collected from
  137. */
  138. @Beta
  139. protected void createCacheFields(Sheet sheet) {
  140. //Get values for start row, start and end column
  141. AreaReference ar = getPivotArea(sheet.getWorkbook());
  142. CellReference firstCell = ar.getFirstCell();
  143. CellReference lastCell = ar.getLastCell();
  144. int columnStart = firstCell.getCol();
  145. int columnEnd = lastCell.getCol();
  146. Row row = sheet.getRow(firstCell.getRow());
  147. CTCacheFields cFields;
  148. if(ctPivotCacheDefinition.getCacheFields() != null) {
  149. cFields = ctPivotCacheDefinition.getCacheFields();
  150. } else {
  151. cFields = ctPivotCacheDefinition.addNewCacheFields();
  152. }
  153. //For each column, create a cache field and give it en empty sharedItems
  154. for(int i=columnStart; i<=columnEnd; i++) {
  155. CTCacheField cf = cFields.addNewCacheField();
  156. if(i==columnEnd){
  157. cFields.setCount(cFields.sizeOfCacheFieldArray());
  158. }
  159. //General number format
  160. cf.setNumFmtId(0);
  161. cf.setName(row.getCell(i).getStringCellValue());
  162. cf.addNewSharedItems();
  163. }
  164. }
  165. }