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.

XSSFSheetXMLHandler.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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 org.apache.poi.ss.usermodel.BuiltinFormats;
  17. import org.apache.poi.ss.usermodel.DataFormatter;
  18. import org.apache.poi.xssf.model.StylesTable;
  19. import org.apache.poi.xssf.usermodel.XSSFCellStyle;
  20. import org.apache.poi.xssf.usermodel.XSSFRichTextString;
  21. import org.xml.sax.Attributes;
  22. import org.xml.sax.SAXException;
  23. import org.xml.sax.helpers.DefaultHandler;
  24. /**
  25. * This class handles the processing of a sheet#.xml
  26. * sheet part of a XSSF .xlsx file, and generates
  27. * row and cell events for it.
  28. */
  29. public class XSSFSheetXMLHandler extends DefaultHandler {
  30. /**
  31. * These are the different kinds of cells we support.
  32. * We keep track of the current one between
  33. * the start and end.
  34. */
  35. enum xssfDataType {
  36. BOOLEAN,
  37. ERROR,
  38. FORMULA,
  39. INLINE_STRING,
  40. SST_STRING,
  41. NUMBER,
  42. }
  43. /**
  44. * Table with the styles used for formatting
  45. */
  46. private StylesTable stylesTable;
  47. private ReadOnlySharedStringsTable sharedStringsTable;
  48. /**
  49. * Where our text is going
  50. */
  51. private final SheetContentsHandler output;
  52. // Set when V start element is seen
  53. private boolean vIsOpen;
  54. // Set when F start element is seen
  55. private boolean fIsOpen;
  56. // Set when an Inline String "is" is seen
  57. private boolean isIsOpen;
  58. // Set when a header/footer element is seen
  59. private boolean hfIsOpen;
  60. // Set when cell start element is seen;
  61. // used when cell close element is seen.
  62. private xssfDataType nextDataType;
  63. // Used to format numeric cell values.
  64. private short formatIndex;
  65. private String formatString;
  66. private final DataFormatter formatter;
  67. private String cellRef;
  68. private boolean formulasNotResults;
  69. // Gathers characters as they are seen.
  70. private StringBuffer value = new StringBuffer();
  71. private StringBuffer formula = new StringBuffer();
  72. private StringBuffer headerFooter = new StringBuffer();
  73. /**
  74. * Accepts objects needed while parsing.
  75. *
  76. * @param styles Table of styles
  77. * @param strings Table of shared strings
  78. */
  79. public XSSFSheetXMLHandler(
  80. StylesTable styles,
  81. ReadOnlySharedStringsTable strings,
  82. SheetContentsHandler sheetContentsHandler,
  83. DataFormatter dataFormatter,
  84. boolean formulasNotResults) {
  85. this.stylesTable = styles;
  86. this.sharedStringsTable = strings;
  87. this.output = sheetContentsHandler;
  88. this.formulasNotResults = formulasNotResults;
  89. this.nextDataType = xssfDataType.NUMBER;
  90. this.formatter = dataFormatter;
  91. }
  92. /**
  93. * Accepts objects needed while parsing.
  94. *
  95. * @param styles Table of styles
  96. * @param strings Table of shared strings
  97. */
  98. public XSSFSheetXMLHandler(
  99. StylesTable styles,
  100. ReadOnlySharedStringsTable strings,
  101. SheetContentsHandler sheetContentsHandler,
  102. boolean formulasNotResults) {
  103. this(styles, strings, sheetContentsHandler, new DataFormatter(), formulasNotResults);
  104. }
  105. private boolean isTextTag(String name) {
  106. if("v".equals(name)) {
  107. // Easy, normal v text tag
  108. return true;
  109. }
  110. if("inlineStr".equals(name)) {
  111. // Easy inline string
  112. return true;
  113. }
  114. if("t".equals(name) && isIsOpen) {
  115. // Inline string <is><t>...</t></is> pair
  116. return true;
  117. }
  118. // It isn't a text tag
  119. return false;
  120. }
  121. @Override
  122. public void startElement(String uri, String localName, String name,
  123. Attributes attributes) throws SAXException {
  124. if (isTextTag(name)) {
  125. vIsOpen = true;
  126. // Clear contents cache
  127. value.setLength(0);
  128. } else if ("is".equals(name)) {
  129. // Inline string outer tag
  130. isIsOpen = true;
  131. } else if ("f".equals(name)) {
  132. // Clear contents cache
  133. formula.setLength(0);
  134. // Mark us as being a formula if not already
  135. if(nextDataType == xssfDataType.NUMBER) {
  136. nextDataType = xssfDataType.FORMULA;
  137. }
  138. // Decide where to get the formula string from
  139. String type = attributes.getValue("t");
  140. if(type != null && type.equals("shared")) {
  141. // Is it the one that defines the shared, or uses it?
  142. String ref = attributes.getValue("ref");
  143. String si = attributes.getValue("si");
  144. if(ref != null) {
  145. // This one defines it
  146. // TODO Save it somewhere
  147. fIsOpen = true;
  148. } else {
  149. // This one uses a shared formula
  150. // TODO Retrieve the shared formula and tweak it to
  151. // match the current cell
  152. if(formulasNotResults) {
  153. System.err.println("Warning - shared formulas not yet supported!");
  154. } else {
  155. // It's a shared formula, so we can't get at the formula string yet
  156. // However, they don't care about the formula string, so that's ok!
  157. }
  158. }
  159. } else {
  160. fIsOpen = true;
  161. }
  162. }
  163. else if("oddHeader".equals(name) || "evenHeader".equals(name) ||
  164. "firstHeader".equals(name) || "firstFooter".equals(name) ||
  165. "oddFooter".equals(name) || "evenFooter".equals(name)) {
  166. hfIsOpen = true;
  167. // Clear contents cache
  168. headerFooter.setLength(0);
  169. }
  170. else if("row".equals(name)) {
  171. int rowNum = Integer.parseInt(attributes.getValue("r")) - 1;
  172. output.startRow(rowNum);
  173. }
  174. // c => cell
  175. else if ("c".equals(name)) {
  176. // Set up defaults.
  177. this.nextDataType = xssfDataType.NUMBER;
  178. this.formatIndex = -1;
  179. this.formatString = null;
  180. cellRef = attributes.getValue("r");
  181. String cellType = attributes.getValue("t");
  182. String cellStyleStr = attributes.getValue("s");
  183. if ("b".equals(cellType))
  184. nextDataType = xssfDataType.BOOLEAN;
  185. else if ("e".equals(cellType))
  186. nextDataType = xssfDataType.ERROR;
  187. else if ("inlineStr".equals(cellType))
  188. nextDataType = xssfDataType.INLINE_STRING;
  189. else if ("s".equals(cellType))
  190. nextDataType = xssfDataType.SST_STRING;
  191. else if ("str".equals(cellType))
  192. nextDataType = xssfDataType.FORMULA;
  193. else {
  194. // Number, but almost certainly with a special style or format
  195. XSSFCellStyle style = null;
  196. if (cellStyleStr != null) {
  197. int styleIndex = Integer.parseInt(cellStyleStr);
  198. style = stylesTable.getStyleAt(styleIndex);
  199. } else if (stylesTable.getNumCellStyles() > 0) {
  200. style = stylesTable.getStyleAt(0);
  201. }
  202. if (style != null) {
  203. this.formatIndex = style.getDataFormat();
  204. this.formatString = style.getDataFormatString();
  205. if (this.formatString == null)
  206. this.formatString = BuiltinFormats.getBuiltinFormat(this.formatIndex);
  207. }
  208. }
  209. }
  210. }
  211. @Override
  212. public void endElement(String uri, String localName, String name)
  213. throws SAXException {
  214. String thisStr = null;
  215. // v => contents of a cell
  216. if (isTextTag(name)) {
  217. vIsOpen = false;
  218. // Process the value contents as required, now we have it all
  219. switch (nextDataType) {
  220. case BOOLEAN:
  221. char first = value.charAt(0);
  222. thisStr = first == '0' ? "FALSE" : "TRUE";
  223. break;
  224. case ERROR:
  225. thisStr = "ERROR:" + value.toString();
  226. break;
  227. case FORMULA:
  228. if(formulasNotResults) {
  229. thisStr = formula.toString();
  230. } else {
  231. String fv = value.toString();
  232. if (this.formatString != null) {
  233. try {
  234. // Try to use the value as a formattable number
  235. double d = Double.parseDouble(fv);
  236. thisStr = formatter.formatRawCellContents(d, this.formatIndex, this.formatString);
  237. } catch(NumberFormatException e) {
  238. // Formula is a String result not a Numeric one
  239. thisStr = fv;
  240. }
  241. } else {
  242. // No formating applied, just do raw value in all cases
  243. thisStr = fv;
  244. }
  245. }
  246. break;
  247. case INLINE_STRING:
  248. // TODO: Can these ever have formatting on them?
  249. XSSFRichTextString rtsi = new XSSFRichTextString(value.toString());
  250. thisStr = rtsi.toString();
  251. break;
  252. case SST_STRING:
  253. String sstIndex = value.toString();
  254. try {
  255. int idx = Integer.parseInt(sstIndex);
  256. XSSFRichTextString rtss = new XSSFRichTextString(sharedStringsTable.getEntryAt(idx));
  257. thisStr = rtss.toString();
  258. }
  259. catch (NumberFormatException ex) {
  260. System.err.println("Failed to parse SST index '" + sstIndex + "': " + ex.toString());
  261. }
  262. break;
  263. case NUMBER:
  264. String n = value.toString();
  265. if (this.formatString != null)
  266. thisStr = formatter.formatRawCellContents(Double.parseDouble(n), this.formatIndex, this.formatString);
  267. else
  268. thisStr = n;
  269. break;
  270. default:
  271. thisStr = "(TODO: Unexpected type: " + nextDataType + ")";
  272. break;
  273. }
  274. // Output
  275. output.cell(cellRef, thisStr);
  276. } else if ("f".equals(name)) {
  277. fIsOpen = false;
  278. } else if ("is".equals(name)) {
  279. isIsOpen = false;
  280. } else if ("row".equals(name)) {
  281. output.endRow();
  282. }
  283. else if("oddHeader".equals(name) || "evenHeader".equals(name) ||
  284. "firstHeader".equals(name)) {
  285. hfIsOpen = false;
  286. output.headerFooter(headerFooter.toString(), true, name);
  287. }
  288. else if("oddFooter".equals(name) || "evenFooter".equals(name) ||
  289. "firstFooter".equals(name)) {
  290. hfIsOpen = false;
  291. output.headerFooter(headerFooter.toString(), false, name);
  292. }
  293. }
  294. /**
  295. * Captures characters only if a suitable element is open.
  296. * Originally was just "v"; extended for inlineStr also.
  297. */
  298. @Override
  299. public void characters(char[] ch, int start, int length)
  300. throws SAXException {
  301. if (vIsOpen) {
  302. value.append(ch, start, length);
  303. }
  304. if (fIsOpen) {
  305. formula.append(ch, start, length);
  306. }
  307. if (hfIsOpen) {
  308. headerFooter.append(ch, start, length);
  309. }
  310. }
  311. /**
  312. * You need to implement this to handle the results
  313. * of the sheet parsing.
  314. */
  315. public interface SheetContentsHandler {
  316. /** A row with the (zero based) row number has started */
  317. public void startRow(int rowNum);
  318. /** A row with the (zero based) row number has ended */
  319. public void endRow();
  320. /** A cell, with the given formatted value, was encountered */
  321. public void cell(String cellReference, String formattedValue);
  322. /** A header or footer has been encountered */
  323. public void headerFooter(String text, boolean isHeader, String tagName);
  324. }
  325. }