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

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