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.

ReadOnlySharedStringsTable.java 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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.eventusermodel;
  16. import static org.apache.poi.xssf.usermodel.XSSFRelation.NS_SPREADSHEETML;
  17. import javax.xml.parsers.ParserConfigurationException;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.PushbackInputStream;
  21. import java.util.ArrayList;
  22. import java.util.HashMap;
  23. import java.util.List;
  24. import java.util.Map;
  25. import org.apache.poi.openxml4j.opc.OPCPackage;
  26. import org.apache.poi.openxml4j.opc.PackagePart;
  27. import org.apache.poi.util.SAXHelper;
  28. import org.apache.poi.xssf.usermodel.XSSFRelation;
  29. import org.xml.sax.Attributes;
  30. import org.xml.sax.InputSource;
  31. import org.xml.sax.SAXException;
  32. import org.xml.sax.XMLReader;
  33. import org.xml.sax.helpers.DefaultHandler;
  34. /**
  35. * <p>This is a lightweight way to process the Shared Strings
  36. * table. Most of the text cells will reference something
  37. * from in here.
  38. * <p>Note that each SI entry can have multiple T elements, if the
  39. * string is made up of bits with different formatting.
  40. * <p>Example input:
  41. * <pre>
  42. &lt;?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
  43. &lt;sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="2" uniqueCount="2">
  44. &lt;si>
  45. &lt;r>
  46. &lt;rPr>
  47. &lt;b />
  48. &lt;sz val="11" />
  49. &lt;color theme="1" />
  50. &lt;rFont val="Calibri" />
  51. &lt;family val="2" />
  52. &lt;scheme val="minor" />
  53. &lt;/rPr>
  54. &lt;t>This:&lt;/t>
  55. &lt;/r>
  56. &lt;r>
  57. &lt;rPr>
  58. &lt;sz val="11" />
  59. &lt;color theme="1" />
  60. &lt;rFont val="Calibri" />
  61. &lt;family val="2" />
  62. &lt;scheme val="minor" />
  63. &lt;/rPr>
  64. &lt;t xml:space="preserve">Causes Problems&lt;/t>
  65. &lt;/r>
  66. &lt;/si>
  67. &lt;si>
  68. &lt;t>This does not&lt;/t>
  69. &lt;/si>
  70. &lt;/sst>
  71. * </pre>
  72. *
  73. */
  74. public class ReadOnlySharedStringsTable extends DefaultHandler {
  75. /**
  76. * An integer representing the total count of strings in the workbook. This count does not
  77. * include any numbers, it counts only the total of text strings in the workbook.
  78. */
  79. private int count;
  80. /**
  81. * An integer representing the total count of unique strings in the Shared String Table.
  82. * A string is unique even if it is a copy of another string, but has different formatting applied
  83. * at the character level.
  84. */
  85. private int uniqueCount;
  86. /**
  87. * The shared strings table.
  88. */
  89. private List<String> strings;
  90. /**
  91. * Map of phonetic strings (if they exist) indexed
  92. * with the integer matching the index in strings
  93. */
  94. private Map<Integer, String> phoneticStrings;
  95. /**
  96. * @param pkg The {@link OPCPackage} to use as basis for the shared-strings table.
  97. * @throws IOException If reading the data from the package fails.
  98. * @throws SAXException if parsing the XML data fails.
  99. */
  100. public ReadOnlySharedStringsTable(OPCPackage pkg)
  101. throws IOException, SAXException {
  102. ArrayList<PackagePart> parts =
  103. pkg.getPartsByContentType(XSSFRelation.SHARED_STRINGS.getContentType());
  104. // Some workbooks have no shared strings table.
  105. if (parts.size() > 0) {
  106. PackagePart sstPart = parts.get(0);
  107. readFrom(sstPart.getInputStream());
  108. }
  109. }
  110. /**
  111. * Like POIXMLDocumentPart constructor
  112. *
  113. * @since POI 3.14-Beta1
  114. */
  115. public ReadOnlySharedStringsTable(PackagePart part) throws IOException, SAXException {
  116. readFrom(part.getInputStream());
  117. }
  118. /**
  119. * Read this shared strings table from an XML file.
  120. *
  121. * @param is The input stream containing the XML document.
  122. * @throws IOException if an error occurs while reading.
  123. * @throws SAXException if parsing the XML data fails.
  124. */
  125. public void readFrom(InputStream is) throws IOException, SAXException {
  126. // test if the file is empty, otherwise parse it
  127. PushbackInputStream pis = new PushbackInputStream(is, 1);
  128. int emptyTest = pis.read();
  129. if (emptyTest > -1) {
  130. pis.unread(emptyTest);
  131. InputSource sheetSource = new InputSource(pis);
  132. try {
  133. XMLReader sheetParser = SAXHelper.newXMLReader();
  134. sheetParser.setContentHandler(this);
  135. sheetParser.parse(sheetSource);
  136. } catch(ParserConfigurationException e) {
  137. throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());
  138. }
  139. }
  140. }
  141. /**
  142. * Return an integer representing the total count of strings in the workbook. This count does not
  143. * include any numbers, it counts only the total of text strings in the workbook.
  144. *
  145. * @return the total count of strings in the workbook
  146. */
  147. public int getCount() {
  148. return this.count;
  149. }
  150. /**
  151. * Returns an integer representing the total count of unique strings in the Shared String Table.
  152. * A string is unique even if it is a copy of another string, but has different formatting applied
  153. * at the character level.
  154. *
  155. * @return the total count of unique strings in the workbook
  156. */
  157. public int getUniqueCount() {
  158. return this.uniqueCount;
  159. }
  160. /**
  161. * Return the string at a given index.
  162. * Formatting is ignored.
  163. *
  164. * @param idx index of item to return.
  165. * @return the item at the specified position in this Shared String table.
  166. */
  167. public String getEntryAt(int idx) {
  168. return strings.get(idx);
  169. }
  170. /**
  171. * Return the phonetic string at a given index.
  172. * Returns <code>null</code> if no phonetic string
  173. * exists at that index.
  174. * @param idx
  175. * @return
  176. */
  177. public String getPhoneticStringAt(int idx) {
  178. //avoid an NPE. If the parser hasn't
  179. //yet hit <sst/> phoneticStrings could be null
  180. if (phoneticStrings == null) {
  181. return null;
  182. }
  183. return phoneticStrings.get(idx);
  184. }
  185. public List<String> getItems() {
  186. return strings;
  187. }
  188. //// ContentHandler methods ////
  189. private StringBuffer characters;
  190. private StringBuffer rphCharacters;
  191. private boolean tIsOpen;
  192. private boolean inRPh;
  193. public void startElement(String uri, String localName, String name,
  194. Attributes attributes) throws SAXException {
  195. if (uri != null && ! uri.equals(NS_SPREADSHEETML)) {
  196. return;
  197. }
  198. if ("sst".equals(localName)) {
  199. String count = attributes.getValue("count");
  200. if(count != null) this.count = Integer.parseInt(count);
  201. String uniqueCount = attributes.getValue("uniqueCount");
  202. if(uniqueCount != null) this.uniqueCount = Integer.parseInt(uniqueCount);
  203. this.strings = new ArrayList<String>(this.uniqueCount);
  204. this.phoneticStrings = new HashMap<Integer, String>();
  205. characters = new StringBuffer();
  206. rphCharacters = new StringBuffer();
  207. } else if ("si".equals(localName)) {
  208. characters.setLength(0);
  209. } else if ("t".equals(localName)) {
  210. tIsOpen = true;
  211. } else if ("rPh".equals(localName)) {
  212. inRPh = true;
  213. }
  214. }
  215. public void endElement(String uri, String localName, String name)
  216. throws SAXException {
  217. if (uri != null && ! uri.equals(NS_SPREADSHEETML)) {
  218. return;
  219. }
  220. if ("si".equals(localName)) {
  221. strings.add(characters.toString());
  222. if (rphCharacters.length() > 0) {
  223. phoneticStrings.put(strings.size()-1, rphCharacters.toString());
  224. rphCharacters.setLength(0);
  225. }
  226. } else if ("t".equals(localName)) {
  227. tIsOpen = false;
  228. } else if ("rPh".equals(localName)) {
  229. inRPh = false;
  230. }
  231. }
  232. /**
  233. * Captures characters only if a t(ext) element is open.
  234. */
  235. public void characters(char[] ch, int start, int length)
  236. throws SAXException {
  237. if (tIsOpen) {
  238. if (inRPh) {
  239. rphCharacters.append(ch, start, length);
  240. } else {
  241. characters.append(ch, start, length);
  242. }
  243. }
  244. }
  245. }