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.

EventBasedExcelExtractor.java 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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 java.io.Closeable;
  17. import java.io.IOException;
  18. import java.util.ArrayList;
  19. import java.util.List;
  20. import org.apache.poi.POIDocument;
  21. import org.apache.poi.extractor.POIOLE2TextExtractor;
  22. import org.apache.poi.hpsf.DocumentSummaryInformation;
  23. import org.apache.poi.hpsf.SummaryInformation;
  24. import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener;
  25. import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
  26. import org.apache.poi.hssf.eventusermodel.HSSFListener;
  27. import org.apache.poi.hssf.eventusermodel.HSSFRequest;
  28. import org.apache.poi.hssf.model.HSSFFormulaParser;
  29. import org.apache.poi.hssf.record.BOFRecord;
  30. import org.apache.poi.hssf.record.BoundSheetRecord;
  31. import org.apache.poi.hssf.record.FormulaRecord;
  32. import org.apache.poi.hssf.record.LabelRecord;
  33. import org.apache.poi.hssf.record.LabelSSTRecord;
  34. import org.apache.poi.hssf.record.NoteRecord;
  35. import org.apache.poi.hssf.record.NumberRecord;
  36. import org.apache.poi.hssf.record.SSTRecord;
  37. import org.apache.poi.hssf.record.StringRecord;
  38. import org.apache.poi.poifs.filesystem.DirectoryEntry;
  39. import org.apache.poi.poifs.filesystem.DirectoryNode;
  40. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  41. /**
  42. * A text extractor for Excel files, that is based
  43. * on the HSSF EventUserModel API.
  44. * It will typically use less memory than
  45. * {@link ExcelExtractor}, but may not provide
  46. * the same richness of formatting.
  47. * Returns the textual content of the file, suitable for
  48. * indexing by something like Lucene, but not really
  49. * intended for display to the user.
  50. * <p>
  51. * To turn an excel file into a CSV or similar, then see
  52. * the XLS2CSVmra example
  53. * </p>
  54. *
  55. * @see <a href="http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/hssf/eventusermodel/examples/XLS2CSVmra.java">XLS2CSVmra</a>
  56. */
  57. public class EventBasedExcelExtractor implements POIOLE2TextExtractor, org.apache.poi.ss.extractor.ExcelExtractor {
  58. private final POIFSFileSystem poifs;
  59. private final DirectoryNode _dir;
  60. private boolean doCloseFilesystem = true;
  61. boolean _includeSheetNames = true;
  62. boolean _formulasNotResults;
  63. public EventBasedExcelExtractor(DirectoryNode dir) {
  64. poifs = null;
  65. _dir = dir;
  66. }
  67. public EventBasedExcelExtractor(POIFSFileSystem fs) {
  68. poifs = fs;
  69. _dir = fs.getRoot();
  70. }
  71. /**
  72. * Would return the document information metadata for the document,
  73. * if we supported it
  74. */
  75. @Override
  76. public DocumentSummaryInformation getDocSummaryInformation() {
  77. throw new IllegalStateException("Metadata extraction not supported in streaming mode, please use ExcelExtractor");
  78. }
  79. /**
  80. * Would return the summary information metadata for the document,
  81. * if we supported it
  82. */
  83. @Override
  84. public SummaryInformation getSummaryInformation() {
  85. throw new IllegalStateException("Metadata extraction not supported in streaming mode, please use ExcelExtractor");
  86. }
  87. /**
  88. * Would control the inclusion of cell comments from the document,
  89. * if we supported it
  90. */
  91. public void setIncludeCellComments(boolean includeComments) {
  92. throw new IllegalStateException("Comment extraction not supported in streaming mode, please use ExcelExtractor");
  93. }
  94. /**
  95. * Would control the inclusion of headers and footers from the document,
  96. * if we supported it
  97. */
  98. public void setIncludeHeadersFooters(boolean includeHeadersFooters) {
  99. throw new IllegalStateException("Header/Footer extraction not supported in streaming mode, please use ExcelExtractor");
  100. }
  101. /**
  102. * Should sheet names be included? Default is true
  103. */
  104. public void setIncludeSheetNames(boolean includeSheetNames) {
  105. _includeSheetNames = includeSheetNames;
  106. }
  107. /**
  108. * Should we return the formula itself, and not
  109. * the result it produces? Default is false
  110. */
  111. public void setFormulasNotResults(boolean formulasNotResults) {
  112. _formulasNotResults = formulasNotResults;
  113. }
  114. /**
  115. * Retreives the text contents of the file
  116. */
  117. public String getText() {
  118. String text;
  119. try {
  120. TextListener tl = triggerExtraction();
  121. text = tl._text.toString();
  122. if(! text.endsWith("\n")) {
  123. text = text + "\n";
  124. }
  125. } catch(IOException e) {
  126. throw new RuntimeException(e);
  127. }
  128. return text;
  129. }
  130. private TextListener triggerExtraction() throws IOException {
  131. TextListener tl = new TextListener();
  132. FormatTrackingHSSFListener ft = new FormatTrackingHSSFListener(tl);
  133. tl._ft = ft;
  134. // Register and process
  135. HSSFEventFactory factory = new HSSFEventFactory();
  136. HSSFRequest request = new HSSFRequest();
  137. request.addListenerForAllRecords(ft);
  138. factory.processWorkbookEvents(request, _dir);
  139. return tl;
  140. }
  141. private class TextListener implements HSSFListener {
  142. FormatTrackingHSSFListener _ft;
  143. private SSTRecord sstRecord;
  144. private final List<String> sheetNames;
  145. final StringBuilder _text = new StringBuilder();
  146. private int sheetNum = -1;
  147. private int rowNum;
  148. private boolean outputNextStringValue;
  149. private int nextRow = -1;
  150. public TextListener() {
  151. sheetNames = new ArrayList<>();
  152. }
  153. public void processRecord(org.apache.poi.hssf.record.Record record) {
  154. String thisText = null;
  155. int thisRow = -1;
  156. switch(record.getSid()) {
  157. case BoundSheetRecord.sid:
  158. BoundSheetRecord sr = (BoundSheetRecord)record;
  159. sheetNames.add(sr.getSheetname());
  160. break;
  161. case BOFRecord.sid:
  162. BOFRecord bof = (BOFRecord)record;
  163. if(bof.getType() == BOFRecord.TYPE_WORKSHEET) {
  164. sheetNum++;
  165. rowNum = -1;
  166. if(_includeSheetNames) {
  167. if(_text.length() > 0) _text.append("\n");
  168. _text.append(sheetNames.get(sheetNum));
  169. }
  170. }
  171. break;
  172. case SSTRecord.sid:
  173. sstRecord = (SSTRecord)record;
  174. break;
  175. case FormulaRecord.sid:
  176. FormulaRecord frec = (FormulaRecord) record;
  177. thisRow = frec.getRow();
  178. if(_formulasNotResults) {
  179. thisText = HSSFFormulaParser.toFormulaString(null, frec.getParsedExpression());
  180. } else {
  181. if(frec.hasCachedResultString()) {
  182. // Formula result is a string
  183. // This is stored in the next record
  184. outputNextStringValue = true;
  185. nextRow = frec.getRow();
  186. } else {
  187. thisText = _ft.formatNumberDateCell(frec);
  188. }
  189. }
  190. break;
  191. case StringRecord.sid:
  192. if(outputNextStringValue) {
  193. // String for formula
  194. StringRecord srec = (StringRecord)record;
  195. thisText = srec.getString();
  196. thisRow = nextRow;
  197. outputNextStringValue = false;
  198. }
  199. break;
  200. case LabelRecord.sid:
  201. LabelRecord lrec = (LabelRecord) record;
  202. thisRow = lrec.getRow();
  203. thisText = lrec.getValue();
  204. break;
  205. case LabelSSTRecord.sid:
  206. LabelSSTRecord lsrec = (LabelSSTRecord) record;
  207. thisRow = lsrec.getRow();
  208. if(sstRecord == null) {
  209. throw new IllegalStateException("No SST record found");
  210. }
  211. thisText = sstRecord.getString(lsrec.getSSTIndex()).toString();
  212. break;
  213. case NoteRecord.sid:
  214. NoteRecord nrec = (NoteRecord) record;
  215. thisRow = nrec.getRow();
  216. // TODO: Find object to match nrec.getShapeId()
  217. break;
  218. case NumberRecord.sid:
  219. NumberRecord numrec = (NumberRecord) record;
  220. thisRow = numrec.getRow();
  221. thisText = _ft.formatNumberDateCell(numrec);
  222. break;
  223. default:
  224. break;
  225. }
  226. if(thisText != null) {
  227. if(thisRow != rowNum) {
  228. rowNum = thisRow;
  229. if(_text.length() > 0)
  230. _text.append("\n");
  231. } else {
  232. _text.append("\t");
  233. }
  234. _text.append(thisText);
  235. }
  236. }
  237. }
  238. @Override
  239. public void setCloseFilesystem(boolean doCloseFilesystem) {
  240. this.doCloseFilesystem = doCloseFilesystem;
  241. }
  242. @Override
  243. public boolean isCloseFilesystem() {
  244. return doCloseFilesystem;
  245. }
  246. @Override
  247. public Closeable getFilesystem() {
  248. return poifs;
  249. }
  250. @Override
  251. public POIDocument getDocument() {
  252. return null;
  253. }
  254. @Override
  255. public DirectoryEntry getRoot() {
  256. return _dir;
  257. }
  258. }