Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

ReadOnlySharedStringsTable.java 10KB

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