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

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