Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

XSSFEventBasedExcelExtractor.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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.CommentsTable;
  38. import org.apache.poi.xssf.model.StylesTable;
  39. import org.apache.poi.xssf.usermodel.XSSFComment;
  40. import org.apache.poi.xssf.usermodel.XSSFShape;
  41. import org.apache.poi.xssf.usermodel.XSSFSimpleShape;
  42. import org.apache.xmlbeans.XmlException;
  43. import org.xml.sax.ContentHandler;
  44. import org.xml.sax.InputSource;
  45. import org.xml.sax.SAXException;
  46. import org.xml.sax.XMLReader;
  47. /**
  48. * Implementation of a text extractor from OOXML Excel
  49. * files that uses SAX event based parsing.
  50. */
  51. public class XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
  52. implements org.apache.poi.ss.extractor.ExcelExtractor {
  53. private OPCPackage container;
  54. private POIXMLProperties properties;
  55. private Locale locale;
  56. private boolean includeTextBoxes = true;
  57. private boolean includeSheetNames = true;
  58. private boolean includeCellComments = false;
  59. private boolean includeHeadersFooters = true;
  60. private boolean formulasNotResults = false;
  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. public void setLocale(Locale locale) {
  112. this.locale = locale;
  113. }
  114. /**
  115. * Returns the opened OPCPackage container.
  116. */
  117. @Override
  118. public OPCPackage getPackage() {
  119. return container;
  120. }
  121. /**
  122. * Returns the core document properties
  123. */
  124. @Override
  125. public CoreProperties getCoreProperties() {
  126. return properties.getCoreProperties();
  127. }
  128. /**
  129. * Returns the extended document properties
  130. */
  131. @Override
  132. public ExtendedProperties getExtendedProperties() {
  133. return properties.getExtendedProperties();
  134. }
  135. /**
  136. * Returns the custom document properties
  137. */
  138. @Override
  139. public CustomProperties getCustomProperties() {
  140. return properties.getCustomProperties();
  141. }
  142. /**
  143. * Processes the given sheet
  144. */
  145. public void processSheet(
  146. SheetContentsHandler sheetContentsExtractor,
  147. StylesTable styles,
  148. CommentsTable comments,
  149. ReadOnlySharedStringsTable strings,
  150. InputStream sheetInputStream)
  151. throws IOException, SAXException {
  152. DataFormatter formatter;
  153. if(locale == null) {
  154. formatter = new DataFormatter();
  155. } else {
  156. formatter = new DataFormatter(locale);
  157. }
  158. InputSource sheetSource = new InputSource(sheetInputStream);
  159. SAXParserFactory saxFactory = SAXParserFactory.newInstance();
  160. try {
  161. SAXParser saxParser = saxFactory.newSAXParser();
  162. XMLReader sheetParser = saxParser.getXMLReader();
  163. ContentHandler handler = new XSSFSheetXMLHandler(
  164. styles, comments, strings, sheetContentsExtractor, formatter, formulasNotResults);
  165. sheetParser.setContentHandler(handler);
  166. sheetParser.parse(sheetSource);
  167. } catch(ParserConfigurationException e) {
  168. throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());
  169. }
  170. }
  171. /**
  172. * Processes the file and returns the text
  173. */
  174. public String getText() {
  175. try {
  176. ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(container);
  177. XSSFReader xssfReader = new XSSFReader(container);
  178. StylesTable styles = xssfReader.getStylesTable();
  179. XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
  180. StringBuffer text = new StringBuffer();
  181. SheetTextExtractor sheetExtractor = new SheetTextExtractor();
  182. while (iter.hasNext()) {
  183. InputStream stream = iter.next();
  184. if(includeSheetNames) {
  185. text.append(iter.getSheetName());
  186. text.append('\n');
  187. }
  188. CommentsTable comments = includeCellComments ? iter.getSheetComments() : null;
  189. processSheet(sheetExtractor, styles, comments, strings, stream);
  190. if (includeHeadersFooters) {
  191. sheetExtractor.appendHeaderText(text);
  192. }
  193. sheetExtractor.appendCellText(text);
  194. if (includeTextBoxes){
  195. processShapes(iter.getShapes(), text);
  196. }
  197. if (includeHeadersFooters) {
  198. sheetExtractor.appendFooterText(text);
  199. }
  200. sheetExtractor.reset();
  201. stream.close();
  202. }
  203. return text.toString();
  204. } catch(IOException e) {
  205. System.err.println(e);
  206. return null;
  207. } catch(SAXException se) {
  208. System.err.println(se);
  209. return null;
  210. } catch(OpenXML4JException o4je) {
  211. System.err.println(o4je);
  212. return null;
  213. }
  214. }
  215. private void processShapes(List<XSSFShape> shapes, StringBuffer text) {
  216. if (shapes == null){
  217. return;
  218. }
  219. for (XSSFShape shape : shapes){
  220. if (shape instanceof XSSFSimpleShape){
  221. String sText = ((XSSFSimpleShape)shape).getText();
  222. if (sText != null && sText.length() > 0){
  223. text.append(sText).append('\n');
  224. }
  225. }
  226. }
  227. }
  228. @Override
  229. public void close() throws IOException {
  230. if (container != null) {
  231. container.close();
  232. container = null;
  233. }
  234. super.close();
  235. }
  236. protected class SheetTextExtractor implements SheetContentsHandler {
  237. private final StringBuffer output;
  238. private boolean firstCellOfRow;
  239. private final Map<String, String> headerFooterMap;
  240. protected SheetTextExtractor() {
  241. this.output = new StringBuffer();
  242. this.firstCellOfRow = true;
  243. this.headerFooterMap = includeHeadersFooters ? new HashMap<String, String>() : null;
  244. }
  245. public void startRow(int rowNum) {
  246. firstCellOfRow = true;
  247. }
  248. public void endRow(int rowNum) {
  249. output.append('\n');
  250. }
  251. public void cell(String cellRef, String formattedValue, XSSFComment comment) {
  252. if(firstCellOfRow) {
  253. firstCellOfRow = false;
  254. } else {
  255. output.append('\t');
  256. }
  257. if (formattedValue != null) {
  258. output.append(formattedValue);
  259. }
  260. if (includeCellComments && comment != null) {
  261. String commentText = comment.getString().getString().replace('\n', ' ');
  262. output.append(formattedValue != null ? " Comment by " : "Comment by ");
  263. if (commentText.startsWith(comment.getAuthor() + ": ")) {
  264. output.append(commentText);
  265. } else {
  266. output.append(comment.getAuthor()).append(": ").append(commentText);
  267. }
  268. }
  269. }
  270. public void emptyCellComment(String cellRef, XSSFComment comment) {
  271. cell(cellRef, null, comment);
  272. }
  273. public void headerFooter(String text, boolean isHeader, String tagName) {
  274. if (headerFooterMap != null) {
  275. headerFooterMap.put(tagName, text);
  276. }
  277. }
  278. /**
  279. * Append the text for the named header or footer if found.
  280. */
  281. private void appendHeaderFooterText(StringBuffer buffer, String name) {
  282. String text = headerFooterMap.get(name);
  283. if (text != null && text.length() > 0) {
  284. // this is a naive way of handling the left, center, and right
  285. // header and footer delimiters, but it seems to be as good as
  286. // the method used by XSSFExcelExtractor
  287. text = handleHeaderFooterDelimiter(text, "&L");
  288. text = handleHeaderFooterDelimiter(text, "&C");
  289. text = handleHeaderFooterDelimiter(text, "&R");
  290. buffer.append(text).append('\n');
  291. }
  292. }
  293. /**
  294. * Remove the delimiter if its found at the beginning of the text,
  295. * or replace it with a tab if its in the middle.
  296. */
  297. private String handleHeaderFooterDelimiter(String text, String delimiter) {
  298. int index = text.indexOf(delimiter);
  299. if (index == 0) {
  300. text = text.substring(2);
  301. } else if (index > 0) {
  302. text = text.substring(0, index) + "\t" + text.substring(index + 2);
  303. }
  304. return text;
  305. }
  306. /**
  307. * Append the text for each header type in the same order
  308. * they are appended in XSSFExcelExtractor.
  309. * @see XSSFExcelExtractor#getText()
  310. * @see org.apache.poi.hssf.extractor.ExcelExtractor#_extractHeaderFooter(org.apache.poi.ss.usermodel.HeaderFooter)
  311. */
  312. private void appendHeaderText(StringBuffer buffer) {
  313. appendHeaderFooterText(buffer, "firstHeader");
  314. appendHeaderFooterText(buffer, "oddHeader");
  315. appendHeaderFooterText(buffer, "evenHeader");
  316. }
  317. /**
  318. * Append the text for each footer type in the same order
  319. * they are appended in XSSFExcelExtractor.
  320. * @see XSSFExcelExtractor#getText()
  321. * @see org.apache.poi.hssf.extractor.ExcelExtractor#_extractHeaderFooter(org.apache.poi.ss.usermodel.HeaderFooter)
  322. */
  323. private void appendFooterText(StringBuffer buffer) {
  324. // append the text for each footer type in the same order
  325. // they are appended in XSSFExcelExtractor
  326. appendHeaderFooterText(buffer, "firstFooter");
  327. appendHeaderFooterText(buffer, "oddFooter");
  328. appendHeaderFooterText(buffer, "evenFooter");
  329. }
  330. /**
  331. * Append the cell contents we have collected.
  332. */
  333. private void appendCellText(StringBuffer buffer) {
  334. buffer.append(output);
  335. }
  336. /**
  337. * Reset this <code>SheetTextExtractor</code> for the next sheet.
  338. */
  339. private void reset() {
  340. output.setLength(0);
  341. firstCellOfRow = true;
  342. if (headerFooterMap != null) {
  343. headerFooterMap.clear();
  344. }
  345. }
  346. }
  347. }