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.

XSSFBReader.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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 java.io.IOException;
  17. import java.io.InputStream;
  18. import java.util.ArrayList;
  19. import java.util.Arrays;
  20. import java.util.Collections;
  21. import java.util.HashSet;
  22. import java.util.Iterator;
  23. import java.util.LinkedList;
  24. import java.util.List;
  25. import java.util.Set;
  26. import com.zaxxer.sparsebits.SparseBitSet;
  27. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  28. import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
  29. import org.apache.poi.openxml4j.opc.OPCPackage;
  30. import org.apache.poi.openxml4j.opc.PackagePart;
  31. import org.apache.poi.openxml4j.opc.PackagePartName;
  32. import org.apache.poi.openxml4j.opc.PackageRelationship;
  33. import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
  34. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  35. import org.apache.poi.util.IOUtils;
  36. import org.apache.poi.util.LittleEndian;
  37. import org.apache.poi.util.POILogFactory;
  38. import org.apache.poi.util.POILogger;
  39. import org.apache.poi.xssf.binary.XSSFBCommentsTable;
  40. import org.apache.poi.xssf.binary.XSSFBParseException;
  41. import org.apache.poi.xssf.binary.XSSFBParser;
  42. import org.apache.poi.xssf.binary.XSSFBRecordType;
  43. import org.apache.poi.xssf.binary.XSSFBRelation;
  44. import org.apache.poi.xssf.binary.XSSFBStylesTable;
  45. import org.apache.poi.xssf.binary.XSSFBUtils;
  46. import org.apache.poi.xssf.model.CommentsTable;
  47. import org.apache.poi.xssf.usermodel.XSSFRelation;
  48. /**
  49. * Reader for xlsb files.
  50. *
  51. * @since 3.16-beta3
  52. */
  53. public class XSSFBReader extends XSSFReader {
  54. private static final POILogger log = POILogFactory.getLogger(XSSFBReader.class);
  55. private static final Set<String> WORKSHEET_RELS =
  56. Collections.unmodifiableSet(new HashSet<>(
  57. Arrays.asList(new String[]{
  58. XSSFRelation.WORKSHEET.getRelation(),
  59. XSSFRelation.CHARTSHEET.getRelation(),
  60. XSSFRelation.MACRO_SHEET_BIN.getRelation(),
  61. XSSFRelation.INTL_MACRO_SHEET_BIN.getRelation(),
  62. XSSFRelation.DIALOG_SHEET_BIN.getRelation()
  63. })
  64. ));
  65. /**
  66. * Creates a new XSSFReader, for the given package
  67. *
  68. * @param pkg opc package
  69. */
  70. public XSSFBReader(OPCPackage pkg) throws IOException, OpenXML4JException {
  71. super(pkg);
  72. }
  73. /**
  74. * In Excel 2013, the absolute path where the file was last saved may be stored in
  75. * the {@link XSSFBRecordType#BrtAbsPath15} record. The equivalent in ooxml is
  76. * &lt;x15ac:absPath&gt;.
  77. *
  78. * @return absolute path or <code>null</code> if it could not be found.
  79. * @throws IOException when there's a problem with the workbook part's stream
  80. */
  81. public String getAbsPathMetadata() throws IOException {
  82. try (InputStream is = workbookPart.getInputStream()) {
  83. PathExtractor p = new PathExtractor(is);
  84. p.parse();
  85. return p.getPath();
  86. }
  87. }
  88. /**
  89. * Returns an Iterator which will let you get at all the
  90. * different Sheets in turn.
  91. * Each sheet's InputStream is only opened when fetched
  92. * from the Iterator. It's up to you to close the
  93. * InputStreams when done with each one.
  94. */
  95. @Override
  96. public Iterator<InputStream> getSheetsData() throws IOException, InvalidFormatException {
  97. return new SheetIterator(workbookPart);
  98. }
  99. public XSSFBStylesTable getXSSFBStylesTable() throws IOException {
  100. ArrayList<PackagePart> parts = pkg.getPartsByContentType(XSSFBRelation.STYLES_BINARY.getContentType());
  101. if(parts.size() == 0) return null;
  102. // Create the Styles Table, and associate the Themes if present
  103. return new XSSFBStylesTable(parts.get(0).getInputStream());
  104. }
  105. public static class SheetIterator extends XSSFReader.SheetIterator {
  106. /**
  107. * Construct a new SheetIterator
  108. *
  109. * @param wb package part holding workbook.xml
  110. */
  111. private SheetIterator(PackagePart wb) throws IOException {
  112. super(wb);
  113. }
  114. @Override
  115. Set<String> getSheetRelationships() {
  116. return WORKSHEET_RELS;
  117. }
  118. Iterator<XSSFSheetRef> createSheetIteratorFromWB(PackagePart wb) throws IOException {
  119. SheetRefLoader sheetRefLoader = new SheetRefLoader(wb.getInputStream());
  120. sheetRefLoader.parse();
  121. return sheetRefLoader.getSheets().iterator();
  122. }
  123. /**
  124. * Not supported by XSSFBReader's SheetIterator.
  125. * Please use {@link #getXSSFBSheetComments()} instead.
  126. * @return nothing, always throws IllegalArgumentException!
  127. */
  128. @Override
  129. public CommentsTable getSheetComments() {
  130. throw new IllegalArgumentException("Please use getXSSFBSheetComments");
  131. }
  132. public XSSFBCommentsTable getXSSFBSheetComments() {
  133. PackagePart sheetPkg = getSheetPart();
  134. // Do we have a comments relationship? (Only ever one if so)
  135. try {
  136. PackageRelationshipCollection commentsList =
  137. sheetPkg.getRelationshipsByType(XSSFRelation.SHEET_COMMENTS.getRelation());
  138. if (commentsList.size() > 0) {
  139. PackageRelationship comments = commentsList.getRelationship(0);
  140. if (comments == null || comments.getTargetURI() == null) {
  141. return null;
  142. }
  143. PackagePartName commentsName = PackagingURIHelper.createPartName(comments.getTargetURI());
  144. PackagePart commentsPart = sheetPkg.getPackage().getPart(commentsName);
  145. return new XSSFBCommentsTable(commentsPart.getInputStream());
  146. }
  147. } catch (InvalidFormatException | IOException e) {
  148. return null;
  149. }
  150. return null;
  151. }
  152. }
  153. private static class PathExtractor extends XSSFBParser {
  154. private static SparseBitSet RECORDS = new SparseBitSet();
  155. static {
  156. RECORDS.set(XSSFBRecordType.BrtAbsPath15.getId());
  157. }
  158. private String path;
  159. public PathExtractor(InputStream is) {
  160. super(is, RECORDS);
  161. }
  162. @Override
  163. public void handleRecord(int recordType, byte[] data) throws XSSFBParseException {
  164. if (recordType != XSSFBRecordType.BrtAbsPath15.getId()) {
  165. return;
  166. }
  167. StringBuilder sb = new StringBuilder();
  168. XSSFBUtils.readXLWideString(data, 0, sb);
  169. path = sb.toString();
  170. }
  171. /**
  172. *
  173. * @return the path if found, otherwise <code>null</code>
  174. */
  175. String getPath() {
  176. return path;
  177. }
  178. }
  179. private static class SheetRefLoader extends XSSFBParser {
  180. List<XSSFSheetRef> sheets = new LinkedList<>();
  181. private SheetRefLoader(InputStream is) {
  182. super(is);
  183. }
  184. @Override
  185. public void handleRecord(int recordType, byte[] data) throws XSSFBParseException {
  186. if (recordType == XSSFBRecordType.BrtBundleSh.getId()) {
  187. addWorksheet(data);
  188. }
  189. }
  190. private void addWorksheet(byte[] data) {
  191. //try to parse the BrtBundleSh
  192. //if there's an exception, catch it and
  193. //try to figure out if this is one of the old beta-created xlsb files
  194. //or if this is a general exception
  195. try {
  196. tryToAddWorksheet(data);
  197. } catch (XSSFBParseException e) {
  198. if (tryOldFormat(data)) {
  199. log.log(POILogger.WARN, "This file was written with a beta version of Excel. "+
  200. "POI will try to parse the file as a regular xlsb.");
  201. } else {
  202. throw e;
  203. }
  204. }
  205. }
  206. private void tryToAddWorksheet(byte[] data) throws XSSFBParseException {
  207. int offset = 0;
  208. //this is the sheet state #2.5.142
  209. /*long hsShtat =*/ //noinspection ResultOfMethodCallIgnored
  210. LittleEndian.getUInt(data, offset); offset += LittleEndian.INT_SIZE;
  211. long iTabID = LittleEndian.getUInt(data, offset); offset += LittleEndian.INT_SIZE;
  212. //according to #2.4.304
  213. if (iTabID < 1 || iTabID > 0x0000FFFFL) {
  214. throw new XSSFBParseException("table id out of range: "+iTabID);
  215. }
  216. StringBuilder sb = new StringBuilder();
  217. offset += XSSFBUtils.readXLWideString(data, offset, sb);
  218. String relId = sb.toString(); sb.setLength(0);
  219. /*offset +=*/ XSSFBUtils.readXLWideString(data, offset, sb);
  220. String name = sb.toString();
  221. if (relId.trim().length() > 0) {
  222. sheets.add(new XSSFSheetRef(relId, name));
  223. }
  224. }
  225. private boolean tryOldFormat(byte[] data) throws XSSFBParseException {
  226. //undocumented what is contained in these 8 bytes.
  227. //for the non-beta xlsb files, this would be 4, not 8.
  228. int offset = 8;
  229. long iTabID = LittleEndian.getUInt(data, offset); offset += LittleEndian.INT_SIZE;
  230. if (iTabID < 1 || iTabID > 0x0000FFFFL) {
  231. throw new XSSFBParseException("table id out of range: "+iTabID);
  232. }
  233. StringBuilder sb = new StringBuilder();
  234. offset += XSSFBUtils.readXLWideString(data, offset, sb);
  235. String relId = sb.toString();
  236. sb.setLength(0);
  237. offset += XSSFBUtils.readXLWideString(data, offset, sb);
  238. String name = sb.toString();
  239. if (relId.trim().length() > 0) {
  240. sheets.add(new XSSFSheetRef(relId, name));
  241. }
  242. if (offset == data.length) {
  243. return true;
  244. }
  245. return false;
  246. }
  247. List<XSSFSheetRef> getSheets() {
  248. return sheets;
  249. }
  250. }
  251. }