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.

OldExcelExtractor.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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.hssf.extractor;
  16. import static org.apache.poi.hssf.model.InternalWorkbook.OLD_WORKBOOK_DIR_ENTRY_NAME;
  17. import static org.apache.poi.hssf.model.InternalWorkbook.WORKBOOK_DIR_ENTRY_NAMES;
  18. import java.io.BufferedInputStream;
  19. import java.io.Closeable;
  20. import java.io.File;
  21. import java.io.FileInputStream;
  22. import java.io.FileNotFoundException;
  23. import java.io.IOException;
  24. import java.io.InputStream;
  25. import org.apache.poi.EncryptedDocumentException;
  26. import org.apache.poi.extractor.POITextExtractor;
  27. import org.apache.poi.hssf.OldExcelFormatException;
  28. import org.apache.poi.hssf.record.BOFRecord;
  29. import org.apache.poi.hssf.record.CodepageRecord;
  30. import org.apache.poi.hssf.record.FormulaRecord;
  31. import org.apache.poi.hssf.record.NumberRecord;
  32. import org.apache.poi.hssf.record.OldFormulaRecord;
  33. import org.apache.poi.hssf.record.OldLabelRecord;
  34. import org.apache.poi.hssf.record.OldSheetRecord;
  35. import org.apache.poi.hssf.record.OldStringRecord;
  36. import org.apache.poi.hssf.record.RKRecord;
  37. import org.apache.poi.hssf.record.RecordInputStream;
  38. import org.apache.poi.poifs.filesystem.DirectoryNode;
  39. import org.apache.poi.poifs.filesystem.DocumentNode;
  40. import org.apache.poi.poifs.filesystem.FileMagic;
  41. import org.apache.poi.poifs.filesystem.NotOLE2FileException;
  42. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  43. import org.apache.poi.ss.usermodel.CellType;
  44. import org.apache.poi.util.IOUtils;
  45. /**
  46. * A text extractor for old Excel files, which are too old for
  47. * HSSFWorkbook to handle. This includes Excel 95, and very old
  48. * (pre-OLE2) Excel files, such as Excel 4 files.
  49. * <p>
  50. * Returns much (but not all) of the textual content of the file,
  51. * suitable for indexing by something like Apache Lucene, or used
  52. * by Apache Tika, but not really intended for display to the user.
  53. * </p>
  54. */
  55. public class OldExcelExtractor implements POITextExtractor {
  56. private static final int FILE_PASS_RECORD_SID = 0x2f;
  57. //arbitrarily selected; may need to increase
  58. private static final int MAX_RECORD_LENGTH = 100_000;
  59. private RecordInputStream ris;
  60. // sometimes we hold the stream here and thus need to ensure it is closed at some point
  61. private Closeable toClose;
  62. private int biffVersion;
  63. private int fileType;
  64. public OldExcelExtractor(InputStream input) throws IOException {
  65. open(input);
  66. }
  67. public OldExcelExtractor(File f) throws IOException {
  68. POIFSFileSystem poifs = null;
  69. try {
  70. poifs = new POIFSFileSystem(f);
  71. open(poifs);
  72. toClose = poifs;
  73. return;
  74. } catch (OldExcelFormatException | NotOLE2FileException e) {
  75. // will be handled by workaround below
  76. } finally {
  77. if (toClose == null) {
  78. IOUtils.closeQuietly(poifs);
  79. }
  80. }
  81. @SuppressWarnings("resource")
  82. FileInputStream biffStream = new FileInputStream(f); // NOSONAR
  83. try {
  84. open(biffStream);
  85. } catch (IOException | RuntimeException e) {
  86. // ensure that the stream is properly closed here if an Exception
  87. // is thrown while opening
  88. biffStream.close();
  89. toClose.close();
  90. throw e;
  91. }
  92. }
  93. public OldExcelExtractor(POIFSFileSystem fs) throws IOException {
  94. toClose = fs;
  95. open(fs);
  96. }
  97. public OldExcelExtractor(DirectoryNode directory) throws IOException {
  98. toClose = directory.getFileSystem();
  99. open(directory);
  100. }
  101. private void open(InputStream biffStream) throws IOException {
  102. BufferedInputStream bis = (biffStream instanceof BufferedInputStream)
  103. ? (BufferedInputStream)biffStream
  104. : new BufferedInputStream(biffStream, 8);
  105. if (FileMagic.valueOf(bis) == FileMagic.OLE2) {
  106. POIFSFileSystem poifs = new POIFSFileSystem(bis);
  107. try {
  108. open(poifs);
  109. toClose = poifs; // Fixed by GR, we should not close it here
  110. } finally {
  111. if (toClose == null) {
  112. poifs.close();
  113. }
  114. }
  115. } else {
  116. ris = new RecordInputStream(bis);
  117. toClose = bis;
  118. prepare();
  119. }
  120. }
  121. private void open(POIFSFileSystem fs) throws IOException {
  122. open(fs.getRoot());
  123. }
  124. private void open(DirectoryNode directory) throws IOException {
  125. DocumentNode book;
  126. try {
  127. book = (DocumentNode)directory.getEntry(OLD_WORKBOOK_DIR_ENTRY_NAME);
  128. } catch (FileNotFoundException | IllegalArgumentException e) {
  129. // some files have "Workbook" instead
  130. book = (DocumentNode)directory.getEntry(WORKBOOK_DIR_ENTRY_NAMES[0]);
  131. }
  132. if (book == null) {
  133. throw new IOException("No Excel 5/95 Book stream found");
  134. }
  135. ris = new RecordInputStream(directory.createDocumentInputStream(book));
  136. prepare();
  137. }
  138. public static void main(String[] args) throws IOException {
  139. if (args.length < 1) {
  140. System.err.println("Use:");
  141. System.err.println(" OldExcelExtractor <filename>");
  142. System.exit(1);
  143. }
  144. OldExcelExtractor extractor = new OldExcelExtractor(new File(args[0]));
  145. System.out.println(extractor.getText());
  146. extractor.close();
  147. }
  148. private void prepare() {
  149. if (! ris.hasNextRecord()) {
  150. throw new IllegalArgumentException("File contains no records!");
  151. }
  152. ris.nextRecord();
  153. // Work out what version we're dealing with
  154. int bofSid = ris.getSid();
  155. switch (bofSid) {
  156. case BOFRecord.biff2_sid:
  157. biffVersion = 2;
  158. break;
  159. case BOFRecord.biff3_sid:
  160. biffVersion = 3;
  161. break;
  162. case BOFRecord.biff4_sid:
  163. biffVersion = 4;
  164. break;
  165. case BOFRecord.biff5_sid:
  166. biffVersion = 5;
  167. break;
  168. default:
  169. throw new IllegalArgumentException("File does not begin with a BOF, found sid of " + bofSid);
  170. }
  171. // Get the type
  172. BOFRecord bof = new BOFRecord(ris);
  173. fileType = bof.getType();
  174. }
  175. /**
  176. * The Biff version, largely corresponding to the Excel version
  177. *
  178. * @return the Biff version
  179. */
  180. public int getBiffVersion() {
  181. return biffVersion;
  182. }
  183. /**
  184. * The kind of the file, one of {@link BOFRecord#TYPE_WORKSHEET},
  185. * {@link BOFRecord#TYPE_CHART}, {@link BOFRecord#TYPE_EXCEL_4_MACRO}
  186. * or {@link BOFRecord#TYPE_WORKSPACE_FILE}
  187. *
  188. * @return the file type
  189. */
  190. public int getFileType() {
  191. return fileType;
  192. }
  193. /**
  194. * Retrieves the text contents of the file, as best we can
  195. * for these old file formats
  196. *
  197. * @return the text contents of the file
  198. */
  199. public String getText() {
  200. StringBuilder text = new StringBuilder();
  201. // To track formats and encodings
  202. CodepageRecord codepage = null;
  203. // TODO track the XFs and Format Strings
  204. // Process each record in turn, looking for interesting ones
  205. while (ris.hasNextRecord()) {
  206. int sid = ris.getNextSid();
  207. ris.nextRecord();
  208. switch (sid) {
  209. case FILE_PASS_RECORD_SID:
  210. throw new EncryptedDocumentException("Encryption not supported for Old Excel files");
  211. case OldSheetRecord.sid:
  212. OldSheetRecord shr = new OldSheetRecord(ris);
  213. shr.setCodePage(codepage);
  214. text.append("Sheet: ");
  215. text.append(shr.getSheetname());
  216. text.append('\n');
  217. break;
  218. case OldLabelRecord.biff2_sid:
  219. case OldLabelRecord.biff345_sid:
  220. OldLabelRecord lr = new OldLabelRecord(ris);
  221. lr.setCodePage(codepage);
  222. text.append(lr.getValue());
  223. text.append('\n');
  224. break;
  225. case OldStringRecord.biff2_sid:
  226. case OldStringRecord.biff345_sid:
  227. OldStringRecord sr = new OldStringRecord(ris);
  228. sr.setCodePage(codepage);
  229. text.append(sr.getString());
  230. text.append('\n');
  231. break;
  232. case NumberRecord.sid:
  233. NumberRecord nr = new NumberRecord(ris);
  234. handleNumericCell(text, nr.getValue());
  235. break;
  236. case OldFormulaRecord.biff2_sid:
  237. case OldFormulaRecord.biff3_sid:
  238. case OldFormulaRecord.biff4_sid:
  239. // Biff 2 and 5+ share the same SID, due to a bug...
  240. if (biffVersion == 5) {
  241. FormulaRecord fr = new FormulaRecord(ris);
  242. if (fr.getCachedResultTypeEnum() == CellType.NUMERIC) {
  243. handleNumericCell(text, fr.getValue());
  244. }
  245. } else {
  246. OldFormulaRecord fr = new OldFormulaRecord(ris);
  247. if (fr.getCachedResultTypeEnum() == CellType.NUMERIC) {
  248. handleNumericCell(text, fr.getValue());
  249. }
  250. }
  251. break;
  252. case RKRecord.sid:
  253. RKRecord rr = new RKRecord(ris);
  254. handleNumericCell(text, rr.getRKNumber());
  255. break;
  256. case CodepageRecord.sid:
  257. codepage = new CodepageRecord(ris);
  258. break;
  259. default:
  260. ris.readFully(IOUtils.safelyAllocate(ris.remaining(), MAX_RECORD_LENGTH));
  261. }
  262. }
  263. ris = null;
  264. return text.toString();
  265. }
  266. protected void handleNumericCell(StringBuilder text, double value) {
  267. // TODO Need to fetch / use format strings
  268. text.append(value);
  269. text.append('\n');
  270. }
  271. @Override
  272. public POITextExtractor getMetadataTextExtractor() {
  273. return null;
  274. }
  275. @Override
  276. public void setCloseFilesystem(boolean doCloseFilesystem) {
  277. }
  278. @Override
  279. public boolean isCloseFilesystem() {
  280. return toClose != null;
  281. }
  282. @Override
  283. public Closeable getFilesystem() {
  284. return toClose;
  285. }
  286. @Override
  287. public Object getDocument() {
  288. return ris;
  289. }
  290. }