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 14KB

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