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.

XSSFReader.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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.eventusermodel;
  16. import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.util.ArrayList;
  20. import java.util.HashMap;
  21. import java.util.Iterator;
  22. import java.util.LinkedList;
  23. import java.util.List;
  24. import java.util.Map;
  25. import org.apache.poi.POIXMLException;
  26. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  27. import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
  28. import org.apache.poi.openxml4j.opc.OPCPackage;
  29. import org.apache.poi.openxml4j.opc.PackagePart;
  30. import org.apache.poi.openxml4j.opc.PackagePartName;
  31. import org.apache.poi.openxml4j.opc.PackageRelationship;
  32. import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
  33. import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
  34. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  35. import org.apache.poi.xssf.model.CommentsTable;
  36. import org.apache.poi.xssf.model.SharedStringsTable;
  37. import org.apache.poi.xssf.model.StylesTable;
  38. import org.apache.poi.xssf.model.ThemesTable;
  39. import org.apache.poi.xssf.usermodel.XSSFDrawing;
  40. import org.apache.poi.xssf.usermodel.XSSFRelation;
  41. import org.apache.poi.xssf.usermodel.XSSFShape;
  42. import org.apache.xmlbeans.XmlException;
  43. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheet;
  44. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook;
  45. import org.openxmlformats.schemas.spreadsheetml.x2006.main.WorkbookDocument;
  46. /**
  47. * This class makes it easy to get at individual parts
  48. * of an OOXML .xlsx file, suitable for low memory sax
  49. * parsing or similar.
  50. * It makes up the core part of the EventUserModel support
  51. * for XSSF.
  52. */
  53. public class XSSFReader {
  54. private OPCPackage pkg;
  55. private PackagePart workbookPart;
  56. /**
  57. * Creates a new XSSFReader, for the given package
  58. */
  59. public XSSFReader(OPCPackage pkg) throws IOException, OpenXML4JException {
  60. this.pkg = pkg;
  61. PackageRelationship coreDocRelationship = this.pkg.getRelationshipsByType(
  62. PackageRelationshipTypes.CORE_DOCUMENT).getRelationship(0);
  63. // strict OOXML likely not fully supported, see #57699
  64. // this code is similar to POIXMLDocumentPart.getPartFromOPCPackage(), but I could not combine it
  65. // easily due to different return values
  66. if(coreDocRelationship == null) {
  67. if (this.pkg.getRelationshipsByType(
  68. PackageRelationshipTypes.STRICT_CORE_DOCUMENT).getRelationship(0) != null) {
  69. throw new POIXMLException("Strict OOXML isn't currently supported, please see bug #57699");
  70. }
  71. throw new POIXMLException("OOXML file structure broken/invalid - no core document found!");
  72. }
  73. // Get the part that holds the workbook
  74. workbookPart = this.pkg.getPart(coreDocRelationship);
  75. }
  76. /**
  77. * Opens up the Shared Strings Table, parses it, and
  78. * returns a handy object for working with
  79. * shared strings.
  80. */
  81. public SharedStringsTable getSharedStringsTable() throws IOException, InvalidFormatException {
  82. ArrayList<PackagePart> parts = pkg.getPartsByContentType( XSSFRelation.SHARED_STRINGS.getContentType());
  83. return parts.size() == 0 ? null : new SharedStringsTable(parts.get(0), null);
  84. }
  85. /**
  86. * Opens up the Styles Table, parses it, and
  87. * returns a handy object for working with cell styles
  88. */
  89. public StylesTable getStylesTable() throws IOException, InvalidFormatException {
  90. ArrayList<PackagePart> parts = pkg.getPartsByContentType( XSSFRelation.STYLES.getContentType());
  91. if(parts.size() == 0) return null;
  92. // Create the Styles Table, and associate the Themes if present
  93. StylesTable styles = new StylesTable(parts.get(0), null);
  94. parts = pkg.getPartsByContentType( XSSFRelation.THEME.getContentType());
  95. if(parts.size() != 0) {
  96. styles.setTheme(new ThemesTable(parts.get(0), null));
  97. }
  98. return styles;
  99. }
  100. /**
  101. * Returns an InputStream to read the contents of the
  102. * shared strings table.
  103. */
  104. public InputStream getSharedStringsData() throws IOException, InvalidFormatException {
  105. return XSSFRelation.SHARED_STRINGS.getContents(workbookPart);
  106. }
  107. /**
  108. * Returns an InputStream to read the contents of the
  109. * styles table.
  110. */
  111. public InputStream getStylesData() throws IOException, InvalidFormatException {
  112. return XSSFRelation.STYLES.getContents(workbookPart);
  113. }
  114. /**
  115. * Returns an InputStream to read the contents of the
  116. * themes table.
  117. */
  118. public InputStream getThemesData() throws IOException, InvalidFormatException {
  119. return XSSFRelation.THEME.getContents(workbookPart);
  120. }
  121. /**
  122. * Returns an InputStream to read the contents of the
  123. * main Workbook, which contains key overall data for
  124. * the file, including sheet definitions.
  125. */
  126. public InputStream getWorkbookData() throws IOException, InvalidFormatException {
  127. return workbookPart.getInputStream();
  128. }
  129. /**
  130. * Returns an InputStream to read the contents of the
  131. * specified Sheet.
  132. * @param relId The relationId of the sheet, from a r:id on the workbook
  133. */
  134. public InputStream getSheet(String relId) throws IOException, InvalidFormatException {
  135. PackageRelationship rel = workbookPart.getRelationship(relId);
  136. if(rel == null) {
  137. throw new IllegalArgumentException("No Sheet found with r:id " + relId);
  138. }
  139. PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI());
  140. PackagePart sheet = pkg.getPart(relName);
  141. if(sheet == null) {
  142. throw new IllegalArgumentException("No data found for Sheet with r:id " + relId);
  143. }
  144. return sheet.getInputStream();
  145. }
  146. /**
  147. * Returns an Iterator which will let you get at all the
  148. * different Sheets in turn.
  149. * Each sheet's InputStream is only opened when fetched
  150. * from the Iterator. It's up to you to close the
  151. * InputStreams when done with each one.
  152. */
  153. public Iterator<InputStream> getSheetsData() throws IOException, InvalidFormatException {
  154. return new SheetIterator(workbookPart);
  155. }
  156. /**
  157. * Iterator over sheet data.
  158. */
  159. public static class SheetIterator implements Iterator<InputStream> {
  160. /**
  161. * Maps relId and the corresponding PackagePart
  162. */
  163. private Map<String, PackagePart> sheetMap;
  164. /**
  165. * Current CTSheet bean
  166. */
  167. private CTSheet ctSheet;
  168. /**
  169. * Iterator over CTSheet objects, returns sheets in <tt>logical</tt> order.
  170. * We can't rely on the Ooxml4J's relationship iterator because it returns objects in physical order,
  171. * i.e. as they are stored in the underlying package
  172. */
  173. private Iterator<CTSheet> sheetIterator;
  174. /**
  175. * Construct a new SheetIterator
  176. *
  177. * @param wb package part holding workbook.xml
  178. */
  179. private SheetIterator(PackagePart wb) throws IOException {
  180. /**
  181. * The order of sheets is defined by the order of CTSheet elements in workbook.xml
  182. */
  183. try {
  184. //step 1. Map sheet's relationship Id and the corresponding PackagePart
  185. sheetMap = new HashMap<String, PackagePart>();
  186. for(PackageRelationship rel : wb.getRelationships()){
  187. if(rel.getRelationshipType().equals(XSSFRelation.WORKSHEET.getRelation()) ||
  188. rel.getRelationshipType().equals(XSSFRelation.CHARTSHEET.getRelation())){
  189. PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI());
  190. sheetMap.put(rel.getId(), wb.getPackage().getPart(relName));
  191. }
  192. }
  193. //step 2. Read array of CTSheet elements, wrap it in a ArayList and construct an iterator
  194. //Note, using XMLBeans might be expensive, consider refactoring to use SAX or a plain regexp search
  195. CTWorkbook wbBean = WorkbookDocument.Factory.parse(wb.getInputStream(), DEFAULT_XML_OPTIONS).getWorkbook();
  196. sheetIterator = wbBean.getSheets().getSheetList().iterator();
  197. } catch (InvalidFormatException e){
  198. throw new POIXMLException(e);
  199. } catch (XmlException e){
  200. throw new POIXMLException(e);
  201. }
  202. }
  203. /**
  204. * Returns <tt>true</tt> if the iteration has more elements.
  205. *
  206. * @return <tt>true</tt> if the iterator has more elements.
  207. */
  208. public boolean hasNext() {
  209. return sheetIterator.hasNext();
  210. }
  211. /**
  212. * Returns input stream of the next sheet in the iteration
  213. *
  214. * @return input stream of the next sheet in the iteration
  215. */
  216. public InputStream next() {
  217. ctSheet = sheetIterator.next();
  218. String sheetId = ctSheet.getId();
  219. try {
  220. PackagePart sheetPkg = sheetMap.get(sheetId);
  221. return sheetPkg.getInputStream();
  222. } catch(IOException e) {
  223. throw new POIXMLException(e);
  224. }
  225. }
  226. /**
  227. * Returns name of the current sheet
  228. *
  229. * @return name of the current sheet
  230. */
  231. public String getSheetName() {
  232. return ctSheet.getName();
  233. }
  234. /**
  235. * Returns the comments associated with this sheet,
  236. * or null if there aren't any
  237. */
  238. public CommentsTable getSheetComments() {
  239. PackagePart sheetPkg = getSheetPart();
  240. // Do we have a comments relationship? (Only ever one if so)
  241. try {
  242. PackageRelationshipCollection commentsList =
  243. sheetPkg.getRelationshipsByType(XSSFRelation.SHEET_COMMENTS.getRelation());
  244. if(commentsList.size() > 0) {
  245. PackageRelationship comments = commentsList.getRelationship(0);
  246. PackagePartName commentsName = PackagingURIHelper.createPartName(comments.getTargetURI());
  247. PackagePart commentsPart = sheetPkg.getPackage().getPart(commentsName);
  248. return new CommentsTable(commentsPart, comments);
  249. }
  250. } catch (InvalidFormatException e) {
  251. return null;
  252. } catch (IOException e) {
  253. return null;
  254. }
  255. return null;
  256. }
  257. /**
  258. * Returns the shapes associated with this sheet,
  259. * an empty list or null if there is an exception
  260. */
  261. public List<XSSFShape> getShapes() {
  262. PackagePart sheetPkg = getSheetPart();
  263. List<XSSFShape> shapes= new LinkedList<XSSFShape>();
  264. // Do we have a comments relationship? (Only ever one if so)
  265. try {
  266. PackageRelationshipCollection drawingsList = sheetPkg.getRelationshipsByType(XSSFRelation.DRAWINGS.getRelation());
  267. for (int i = 0; i < drawingsList.size(); i++){
  268. PackageRelationship drawings = drawingsList.getRelationship(i);
  269. PackagePartName drawingsName = PackagingURIHelper.createPartName(drawings.getTargetURI());
  270. PackagePart drawingsPart = sheetPkg.getPackage().getPart(drawingsName);
  271. XSSFDrawing drawing = new XSSFDrawing(drawingsPart, drawings);
  272. for (XSSFShape shape : drawing.getShapes()){
  273. shapes.add(shape);
  274. }
  275. }
  276. } catch (XmlException e){
  277. return null;
  278. } catch (InvalidFormatException e) {
  279. return null;
  280. } catch (IOException e) {
  281. return null;
  282. }
  283. return shapes;
  284. }
  285. public PackagePart getSheetPart() {
  286. String sheetId = ctSheet.getId();
  287. return sheetMap.get(sheetId);
  288. }
  289. /**
  290. * We're read only, so remove isn't supported
  291. */
  292. public void remove() {
  293. throw new IllegalStateException("Not supported");
  294. }
  295. }
  296. }