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.

XSSFEventBasedExcelExtractor.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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.extractor;
  16. import java.io.IOException;
  17. import java.io.InputStream;
  18. import java.util.HashMap;
  19. import java.util.List;
  20. import java.util.Locale;
  21. import java.util.Map;
  22. import javax.xml.parsers.ParserConfigurationException;
  23. import javax.xml.parsers.SAXParser;
  24. import javax.xml.parsers.SAXParserFactory;
  25. import org.apache.poi.POIXMLProperties;
  26. import org.apache.poi.POIXMLProperties.CoreProperties;
  27. import org.apache.poi.POIXMLProperties.CustomProperties;
  28. import org.apache.poi.POIXMLProperties.ExtendedProperties;
  29. import org.apache.poi.POIXMLTextExtractor;
  30. import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
  31. import org.apache.poi.openxml4j.opc.OPCPackage;
  32. import org.apache.poi.ss.usermodel.DataFormatter;
  33. import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable;
  34. import org.apache.poi.xssf.eventusermodel.XSSFReader;
  35. import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
  36. import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler.SheetContentsHandler;
  37. import org.apache.poi.xssf.model.StylesTable;
  38. import org.apache.poi.xssf.usermodel.XSSFShape;
  39. import org.apache.poi.xssf.usermodel.XSSFSimpleShape;
  40. import org.apache.xmlbeans.XmlException;
  41. import org.xml.sax.ContentHandler;
  42. import org.xml.sax.InputSource;
  43. import org.xml.sax.SAXException;
  44. import org.xml.sax.XMLReader;
  45. /**
  46. * Implementation of a text extractor from OOXML Excel
  47. * files that uses SAX event based parsing.
  48. */
  49. public class XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
  50. implements org.apache.poi.ss.extractor.ExcelExtractor {
  51. private OPCPackage container;
  52. private POIXMLProperties properties;
  53. private Locale locale;
  54. private boolean includeTextBoxes = true;
  55. private boolean includeSheetNames = true;
  56. private boolean includeHeadersFooters = true;
  57. private boolean formulasNotResults = false;
  58. public XSSFEventBasedExcelExtractor(String path) throws XmlException, OpenXML4JException, IOException {
  59. this(OPCPackage.open(path));
  60. }
  61. public XSSFEventBasedExcelExtractor(OPCPackage container) throws XmlException, OpenXML4JException, IOException {
  62. super(null);
  63. this.container = container;
  64. properties = new POIXMLProperties(container);
  65. }
  66. public static void main(String[] args) throws Exception {
  67. if(args.length < 1) {
  68. System.err.println("Use:");
  69. System.err.println(" XSSFEventBasedExcelExtractor <filename.xlsx>");
  70. System.exit(1);
  71. }
  72. POIXMLTextExtractor extractor =
  73. new XSSFEventBasedExcelExtractor(args[0]);
  74. System.out.println(extractor.getText());
  75. }
  76. /**
  77. * Should sheet names be included? Default is true
  78. */
  79. public void setIncludeSheetNames(boolean includeSheetNames) {
  80. this.includeSheetNames = includeSheetNames;
  81. }
  82. /**
  83. * Should we return the formula itself, and not
  84. * the result it produces? Default is false
  85. */
  86. public void setFormulasNotResults(boolean formulasNotResults) {
  87. this.formulasNotResults = formulasNotResults;
  88. }
  89. /**
  90. * Should headers and footers be included? Default is true
  91. */
  92. public void setIncludeHeadersFooters(boolean includeHeadersFooters) {
  93. this.includeHeadersFooters = includeHeadersFooters;
  94. }
  95. /**
  96. * Should text from textboxes be included? Default is true
  97. */
  98. public void setIncludeTextBoxes(boolean includeTextBoxes) {
  99. this.includeTextBoxes = includeTextBoxes;
  100. }
  101. /**
  102. * Would control the inclusion of cell comments from the document,
  103. * if we supported it
  104. */
  105. public void setIncludeCellComments(boolean includeCellComments) {
  106. throw new IllegalStateException("Comment extraction not supported in streaming mode, please use XSSFExcelExtractor");
  107. }
  108. public void setLocale(Locale locale) {
  109. this.locale = locale;
  110. }
  111. /**
  112. * Returns the opened OPCPackage container.
  113. */
  114. @Override
  115. public OPCPackage getPackage() {
  116. return container;
  117. }
  118. /**
  119. * Returns the core document properties
  120. */
  121. @Override
  122. public CoreProperties getCoreProperties() {
  123. return properties.getCoreProperties();
  124. }
  125. /**
  126. * Returns the extended document properties
  127. */
  128. @Override
  129. public ExtendedProperties getExtendedProperties() {
  130. return properties.getExtendedProperties();
  131. }
  132. /**
  133. * Returns the custom document properties
  134. */
  135. @Override
  136. public CustomProperties getCustomProperties() {
  137. return properties.getCustomProperties();
  138. }
  139. /**
  140. * Processes the given sheet
  141. */
  142. public void processSheet(
  143. SheetContentsHandler sheetContentsExtractor,
  144. StylesTable styles,
  145. ReadOnlySharedStringsTable strings,
  146. InputStream sheetInputStream)
  147. throws IOException, SAXException {
  148. DataFormatter formatter;
  149. if(locale == null) {
  150. formatter = new DataFormatter();
  151. } else {
  152. formatter = new DataFormatter(locale);
  153. }
  154. InputSource sheetSource = new InputSource(sheetInputStream);
  155. SAXParserFactory saxFactory = SAXParserFactory.newInstance();
  156. try {
  157. SAXParser saxParser = saxFactory.newSAXParser();
  158. XMLReader sheetParser = saxParser.getXMLReader();
  159. ContentHandler handler = new XSSFSheetXMLHandler(
  160. styles, strings, sheetContentsExtractor, formatter, formulasNotResults);
  161. sheetParser.setContentHandler(handler);
  162. sheetParser.parse(sheetSource);
  163. } catch(ParserConfigurationException e) {
  164. throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());
  165. }
  166. }
  167. /**
  168. * Processes the file and returns the text
  169. */
  170. public String getText() {
  171. try {
  172. ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(container);
  173. XSSFReader xssfReader = new XSSFReader(container);
  174. StylesTable styles = xssfReader.getStylesTable();
  175. XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
  176. StringBuffer text = new StringBuffer();
  177. SheetTextExtractor sheetExtractor = new SheetTextExtractor();
  178. while (iter.hasNext()) {
  179. InputStream stream = iter.next();
  180. if(includeSheetNames) {
  181. text.append(iter.getSheetName());
  182. text.append('\n');
  183. }
  184. processSheet(sheetExtractor, styles, strings, stream);
  185. if (includeHeadersFooters) {
  186. sheetExtractor.appendHeaderText(text);
  187. }
  188. sheetExtractor.appendCellText(text);
  189. if (includeTextBoxes){
  190. processShapes(iter.getShapes(), text);
  191. }
  192. if (includeHeadersFooters) {
  193. sheetExtractor.appendFooterText(text);
  194. }
  195. sheetExtractor.reset();
  196. stream.close();
  197. }
  198. return text.toString();
  199. } catch(IOException e) {
  200. System.err.println(e);
  201. return null;
  202. } catch(SAXException se) {
  203. System.err.println(se);
  204. return null;
  205. } catch(OpenXML4JException o4je) {
  206. System.err.println(o4je);
  207. return null;
  208. }
  209. }
  210. private void processShapes(List<XSSFShape> shapes, StringBuffer text) {
  211. if (shapes == null){
  212. return;
  213. }
  214. for (XSSFShape shape : shapes){
  215. if (shape instanceof XSSFSimpleShape){
  216. String sText = ((XSSFSimpleShape)shape).getText();
  217. if (sText != null && sText.length() > 0){
  218. text.append(sText).append('\n');
  219. }
  220. }
  221. }
  222. }
  223. @Override
  224. public void close() throws IOException {
  225. if (container != null) {
  226. container.close();
  227. container = null;
  228. }
  229. super.close();
  230. }
  231. protected class SheetTextExtractor implements SheetContentsHandler {
  232. private final StringBuffer output;
  233. private boolean firstCellOfRow;
  234. private final Map<String, String> headerFooterMap;
  235. protected SheetTextExtractor() {
  236. this.output = new StringBuffer();
  237. this.firstCellOfRow = true;
  238. this.headerFooterMap = includeHeadersFooters ? new HashMap<String, String>() : null;
  239. }
  240. public void startRow(int rowNum) {
  241. firstCellOfRow = true;
  242. }
  243. public void endRow() {
  244. output.append('\n');
  245. }
  246. public void cell(String cellRef, String formattedValue) {
  247. if(firstCellOfRow) {
  248. firstCellOfRow = false;
  249. } else {
  250. output.append('\t');
  251. }
  252. output.append(formattedValue);
  253. }
  254. public void headerFooter(String text, boolean isHeader, String tagName) {
  255. if (headerFooterMap != null) {
  256. headerFooterMap.put(tagName, text);
  257. }
  258. }
  259. /**
  260. * Append the text for the named header or footer if found.
  261. */
  262. private void appendHeaderFooterText(StringBuffer buffer, String name) {
  263. String text = headerFooterMap.get(name);
  264. if (text != null && text.length() > 0) {
  265. // this is a naive way of handling the left, center, and right
  266. // header and footer delimiters, but it seems to be as good as
  267. // the method used by XSSFExcelExtractor
  268. text = handleHeaderFooterDelimiter(text, "&L");
  269. text = handleHeaderFooterDelimiter(text, "&C");
  270. text = handleHeaderFooterDelimiter(text, "&R");
  271. buffer.append(text).append('\n');
  272. }
  273. }
  274. /**
  275. * Remove the delimiter if its found at the beginning of the text,
  276. * or replace it with a tab if its in the middle.
  277. */
  278. private String handleHeaderFooterDelimiter(String text, String delimiter) {
  279. int index = text.indexOf(delimiter);
  280. if (index == 0) {
  281. text = text.substring(2);
  282. } else if (index > 0) {
  283. text = text.substring(0, index) + "\t" + text.substring(index + 2);
  284. }
  285. return text;
  286. }
  287. /**
  288. * Append the text for each header type in the same order
  289. * they are appended in XSSFExcelExtractor.
  290. * @see XSSFExcelExtractor#getText()
  291. * @see org.apache.poi.hssf.extractor.ExcelExtractor#_extractHeaderFooter(org.apache.poi.ss.usermodel.HeaderFooter)
  292. */
  293. private void appendHeaderText(StringBuffer buffer) {
  294. appendHeaderFooterText(buffer, "firstHeader");
  295. appendHeaderFooterText(buffer, "oddHeader");
  296. appendHeaderFooterText(buffer, "evenHeader");
  297. }
  298. /**
  299. * Append the text for each footer type in the same order
  300. * they are appended in XSSFExcelExtractor.
  301. * @see XSSFExcelExtractor#getText()
  302. * @see org.apache.poi.hssf.extractor.ExcelExtractor#_extractHeaderFooter(org.apache.poi.ss.usermodel.HeaderFooter)
  303. */
  304. private void appendFooterText(StringBuffer buffer) {
  305. // append the text for each footer type in the same order
  306. // they are appended in XSSFExcelExtractor
  307. appendHeaderFooterText(buffer, "firstFooter");
  308. appendHeaderFooterText(buffer, "oddFooter");
  309. appendHeaderFooterText(buffer, "evenFooter");
  310. }
  311. /**
  312. * Append the cell contents we have collected.
  313. */
  314. private void appendCellText(StringBuffer buffer) {
  315. buffer.append(output);
  316. }
  317. /**
  318. * Reset this <code>SheetTextExtractor</code> for the next sheet.
  319. */
  320. private void reset() {
  321. output.setLength(0);
  322. firstCellOfRow = true;
  323. if (headerFooterMap != null) {
  324. headerFooterMap.clear();
  325. }
  326. }
  327. }
  328. }