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.

WorkbookFactory.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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.ss.usermodel;
  16. import static org.apache.poi.extractor.ExtractorFactory.OOXML_PACKAGE;
  17. import static org.apache.poi.poifs.crypt.EncryptionInfo.ENCRYPTION_INFO_ENTRY;
  18. import java.io.BufferedInputStream;
  19. import java.io.File;
  20. import java.io.FileNotFoundException;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.util.ArrayList;
  24. import java.util.List;
  25. import java.util.ServiceLoader;
  26. import org.apache.poi.EmptyFileException;
  27. import org.apache.poi.EncryptedDocumentException;
  28. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  29. import org.apache.poi.poifs.crypt.Decryptor;
  30. import org.apache.poi.poifs.filesystem.DirectoryNode;
  31. import org.apache.poi.poifs.filesystem.FileMagic;
  32. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  33. /**
  34. * Factory for creating the appropriate kind of Workbook
  35. * (be it {@link HSSFWorkbook} or XSSFWorkbook),
  36. * by auto-detecting from the supplied input.
  37. */
  38. public final class WorkbookFactory {
  39. private static class Singleton {
  40. private static final WorkbookFactory INSTANCE = new WorkbookFactory();
  41. }
  42. private interface ProviderMethod {
  43. Workbook create(WorkbookProvider prov) throws IOException;
  44. }
  45. private final List<WorkbookProvider> provider = new ArrayList<>();
  46. private WorkbookFactory() {
  47. ClassLoader cl = WorkbookFactory.class.getClassLoader();
  48. ServiceLoader.load(WorkbookProvider.class, cl).forEach(provider::add);
  49. }
  50. /**
  51. * Create a new empty Workbook, either XSSF or HSSF depending
  52. * on the parameter
  53. *
  54. * @param xssf If an XSSFWorkbook or a HSSFWorkbook should be created
  55. *
  56. * @return The created workbook
  57. *
  58. * @throws IOException if an error occurs while creating the objects
  59. */
  60. public static Workbook create(boolean xssf) throws IOException {
  61. return wp(xssf ? FileMagic.OOXML : FileMagic.OLE2, WorkbookProvider::create);
  62. }
  63. /**
  64. * Creates a HSSFWorkbook from the given POIFSFileSystem<p>
  65. *
  66. * Note that in order to properly release resources the
  67. * Workbook should be closed after use.
  68. *
  69. * @param fs The {@link POIFSFileSystem} to read the document from
  70. *
  71. * @return The created workbook
  72. *
  73. * @throws IOException if an error occurs while reading the data
  74. */
  75. public static Workbook create(POIFSFileSystem fs) throws IOException {
  76. return create(fs, null);
  77. }
  78. /**
  79. * Creates a Workbook from the given POIFSFileSystem, which may
  80. * be password protected
  81. *
  82. * @param fs The {@link POIFSFileSystem} to read the document from
  83. * @param password The password that should be used or null if no password is necessary.
  84. *
  85. * @return The created Workbook
  86. *
  87. * @throws IOException if an error occurs while reading the data
  88. */
  89. private static Workbook create(final POIFSFileSystem fs, String password) throws IOException {
  90. return create(fs.getRoot(), password);
  91. }
  92. /**
  93. * Creates a Workbook from the given DirectoryNode.
  94. *
  95. * @param root The {@link DirectoryNode} to start reading the document from
  96. *
  97. * @return The created Workbook
  98. *
  99. * @throws IOException if an error occurs while reading the data
  100. */
  101. public static Workbook create(final DirectoryNode root) throws IOException {
  102. return create(root, null);
  103. }
  104. /**
  105. * Creates a Workbook from the given DirectoryNode, which may
  106. * be password protected
  107. *
  108. * @param root The {@link DirectoryNode} to start reading the document from
  109. * @param password The password that should be used or null if no password is necessary.
  110. *
  111. * @return The created Workbook
  112. *
  113. * @throws IOException if an error occurs while reading the data
  114. */
  115. public static Workbook create(final DirectoryNode root, String password) throws IOException {
  116. // Encrypted OOXML files go inside OLE2 containers, is this one?
  117. if (root.hasEntry(Decryptor.DEFAULT_POIFS_ENTRY) || root.hasEntry(OOXML_PACKAGE)) {
  118. return wp(FileMagic.OOXML, w -> w.create(root, password));
  119. } else {
  120. return wp(FileMagic.OLE2, w -> w.create(root, password));
  121. }
  122. }
  123. /**
  124. * Creates the appropriate HSSFWorkbook / XSSFWorkbook from
  125. * the given InputStream.
  126. *
  127. * <p>Your input stream MUST either support mark/reset, or
  128. * be wrapped as a {@link BufferedInputStream}!
  129. * Note that using an {@link InputStream} has a higher memory footprint
  130. * than using a {@link File}.</p>
  131. *
  132. * <p>Note that in order to properly release resources the
  133. * Workbook should be closed after use. Note also that loading
  134. * from an InputStream requires more memory than loading
  135. * from a File, so prefer {@link #create(File)} where possible.
  136. *
  137. * @param inp The {@link InputStream} to read data from.
  138. *
  139. * @return The created Workbook
  140. *
  141. * @throws IOException if an error occurs while reading the data
  142. * @throws EncryptedDocumentException If the Workbook given is password protected
  143. */
  144. public static Workbook create(InputStream inp) throws IOException, EncryptedDocumentException {
  145. return create(inp, null);
  146. }
  147. /**
  148. * Creates the appropriate HSSFWorkbook / XSSFWorkbook from
  149. * the given InputStream, which may be password protected.
  150. *
  151. * <p>Your input stream MUST either support mark/reset, or
  152. * be wrapped as a {@link BufferedInputStream}!
  153. * Note that using an {@link InputStream} has a higher memory footprint
  154. * than using a {@link File}.</p>
  155. *
  156. * <p>Note that in order to properly release resources the
  157. * Workbook should be closed after use. Note also that loading
  158. * from an InputStream requires more memory than loading
  159. * from a File, so prefer {@link #create(File)} where possible.</p>
  160. *
  161. * @param inp The {@link InputStream} to read data from.
  162. * @param password The password that should be used or null if no password is necessary.
  163. *
  164. * @return The created Workbook
  165. *
  166. * @throws IOException if an error occurs while reading the data
  167. * @throws EncryptedDocumentException If the wrong password is given for a protected file
  168. */
  169. public static Workbook create(InputStream inp, String password) throws IOException, EncryptedDocumentException {
  170. InputStream is = FileMagic.prepareToCheckMagic(inp);
  171. byte[] emptyFileCheck = new byte[1];
  172. is.mark(emptyFileCheck.length);
  173. if (is.read(emptyFileCheck) < emptyFileCheck.length) {
  174. throw new EmptyFileException();
  175. }
  176. is.reset();
  177. final FileMagic fm = FileMagic.valueOf(is);
  178. if (FileMagic.OOXML == fm) {
  179. return wp(fm, w -> w.create(is));
  180. }
  181. if (FileMagic.OLE2 != fm) {
  182. throw new IOException("Can't open workbook - unsupported file type: "+fm);
  183. }
  184. POIFSFileSystem poifs = new POIFSFileSystem(is);
  185. boolean isOOXML = poifs.getRoot().hasEntry(ENCRYPTION_INFO_ENTRY);
  186. return wp(isOOXML ? FileMagic.OOXML : fm, w -> w.create(poifs.getRoot(), password));
  187. }
  188. /**
  189. * Creates the appropriate HSSFWorkbook / XSSFWorkbook from
  190. * the given File, which must exist and be readable.
  191. * <p>Note that in order to properly release resources the
  192. * Workbook should be closed after use.
  193. *
  194. * @param file The file to read data from.
  195. *
  196. * @return The created Workbook
  197. *
  198. * @throws IOException if an error occurs while reading the data
  199. * @throws EncryptedDocumentException If the Workbook given is password protected
  200. */
  201. public static Workbook create(File file) throws IOException, EncryptedDocumentException {
  202. return create(file, null);
  203. }
  204. /**
  205. * Creates the appropriate HSSFWorkbook / XSSFWorkbook from
  206. * the given File, which must exist and be readable, and
  207. * may be password protected
  208. * <p>Note that in order to properly release resources the
  209. * Workbook should be closed after use.
  210. *
  211. * @param file The file to read data from.
  212. * @param password The password that should be used or null if no password is necessary.
  213. *
  214. * @return The created Workbook
  215. *
  216. * @throws IOException if an error occurs while reading the data
  217. * @throws EncryptedDocumentException If the wrong password is given for a protected file
  218. */
  219. public static Workbook create(File file, String password) throws IOException, EncryptedDocumentException {
  220. return create(file, password, false);
  221. }
  222. /**
  223. * Creates the appropriate HSSFWorkbook / XSSFWorkbook from
  224. * the given File, which must exist and be readable, and
  225. * may be password protected
  226. * <p>Note that in order to properly release resources the
  227. * Workbook should be closed after use.
  228. *
  229. * @param file The file to read data from.
  230. * @param password The password that should be used or null if no password is necessary.
  231. * @param readOnly If the Workbook should be opened in read-only mode to avoid writing back
  232. * changes when the document is closed.
  233. *
  234. * @return The created Workbook
  235. *
  236. * @throws IOException if an error occurs while reading the data
  237. * @throws EncryptedDocumentException If the wrong password is given for a protected file
  238. */
  239. public static Workbook create(File file, String password, boolean readOnly) throws IOException, EncryptedDocumentException {
  240. if (!file.exists()) {
  241. throw new FileNotFoundException(file.toString());
  242. }
  243. if (file.length() == 0) {
  244. throw new EmptyFileException();
  245. }
  246. FileMagic fm = FileMagic.valueOf(file);
  247. if (fm == FileMagic.OOXML) {
  248. return wp(fm, w -> w.create(file, password, readOnly));
  249. } else if (fm == FileMagic.OLE2) {
  250. final boolean ooxmlEnc;
  251. try (POIFSFileSystem fs = new POIFSFileSystem(file, true)) {
  252. DirectoryNode root = fs.getRoot();
  253. ooxmlEnc = root.hasEntry(Decryptor.DEFAULT_POIFS_ENTRY) || root.hasEntry(OOXML_PACKAGE);
  254. }
  255. return wp(ooxmlEnc ? FileMagic.OOXML : fm, w -> w.create(file, password, readOnly));
  256. }
  257. return null;
  258. }
  259. private static Workbook wp(FileMagic fm, ProviderMethod fun) throws IOException {
  260. for (WorkbookProvider prov : Singleton.INSTANCE.provider) {
  261. if (prov.accepts(fm)) {
  262. return fun.create(prov);
  263. }
  264. }
  265. throw new IOException("Your InputStream was neither an OLE2 stream, nor an OOXML stream " +
  266. "or you haven't provide the poi-ooxml*.jar in the classpath/modulepath - FileMagic: "+fm);
  267. }
  268. public static void addProvider(WorkbookProvider provider){
  269. Singleton.INSTANCE.provider.add(provider);
  270. }
  271. public static void removeProvider(Class<? extends WorkbookProvider> provider){
  272. Singleton.INSTANCE.provider.removeIf(p -> p.getClass().getName().equals(provider.getName()));
  273. }
  274. }