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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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 java.util.Comparator;
  17. import java.util.LinkedList;
  18. import java.util.List;
  19. import java.util.Queue;
  20. import org.apache.poi.ss.usermodel.BuiltinFormats;
  21. import org.apache.poi.ss.usermodel.DataFormatter;
  22. import org.apache.poi.ss.util.CellReference;
  23. import org.apache.poi.util.POILogFactory;
  24. import org.apache.poi.util.POILogger;
  25. import org.apache.poi.xssf.model.CommentsTable;
  26. import org.apache.poi.xssf.model.StylesTable;
  27. import org.apache.poi.xssf.usermodel.XSSFCellStyle;
  28. import org.apache.poi.xssf.usermodel.XSSFComment;
  29. import org.apache.poi.xssf.usermodel.XSSFRichTextString;
  30. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComment;
  31. import org.xml.sax.Attributes;
  32. import org.xml.sax.SAXException;
  33. import org.xml.sax.helpers.DefaultHandler;
  34. /**
  35. * This class handles the processing of a sheet#.xml
  36. * sheet part of a XSSF .xlsx file, and generates
  37. * row and cell events for it.
  38. */
  39. public class XSSFSheetXMLHandler extends DefaultHandler {
  40. private static final POILogger logger = POILogFactory.getLogger(XSSFSheetXMLHandler.class);
  41. /**
  42. * These are the different kinds of cells we support.
  43. * We keep track of the current one between
  44. * the start and end.
  45. */
  46. enum xssfDataType {
  47. BOOLEAN,
  48. ERROR,
  49. FORMULA,
  50. INLINE_STRING,
  51. SST_STRING,
  52. NUMBER,
  53. }
  54. /**
  55. * Table with the styles used for formatting
  56. */
  57. private StylesTable stylesTable;
  58. /**
  59. * Table with cell comments
  60. */
  61. private CommentsTable commentsTable;
  62. /**
  63. * Read only access to the shared strings table, for looking
  64. * up (most) string cell's contents
  65. */
  66. private ReadOnlySharedStringsTable sharedStringsTable;
  67. /**
  68. * Where our text is going
  69. */
  70. private final SheetContentsHandler output;
  71. // Set when V start element is seen
  72. private boolean vIsOpen;
  73. // Set when F start element is seen
  74. private boolean fIsOpen;
  75. // Set when an Inline String "is" is seen
  76. private boolean isIsOpen;
  77. // Set when a header/footer element is seen
  78. private boolean hfIsOpen;
  79. // Set when cell start element is seen;
  80. // used when cell close element is seen.
  81. private xssfDataType nextDataType;
  82. // Used to format numeric cell values.
  83. private short formatIndex;
  84. private String formatString;
  85. private final DataFormatter formatter;
  86. private int rowNum;
  87. private String cellRef;
  88. private boolean formulasNotResults;
  89. // Gathers characters as they are seen.
  90. private StringBuffer value = new StringBuffer();
  91. private StringBuffer formula = new StringBuffer();
  92. private StringBuffer headerFooter = new StringBuffer();
  93. private Queue<CellReference> commentCellRefs;
  94. /**
  95. * Accepts objects needed while parsing.
  96. *
  97. * @param styles Table of styles
  98. * @param strings Table of shared strings
  99. */
  100. public XSSFSheetXMLHandler(
  101. StylesTable styles,
  102. CommentsTable comments,
  103. ReadOnlySharedStringsTable strings,
  104. SheetContentsHandler sheetContentsHandler,
  105. DataFormatter dataFormatter,
  106. boolean formulasNotResults) {
  107. this.stylesTable = styles;
  108. this.commentsTable = comments;
  109. this.sharedStringsTable = strings;
  110. this.output = sheetContentsHandler;
  111. this.formulasNotResults = formulasNotResults;
  112. this.nextDataType = xssfDataType.NUMBER;
  113. this.formatter = dataFormatter;
  114. init();
  115. }
  116. /**
  117. * Accepts objects needed while parsing.
  118. *
  119. * @param styles Table of styles
  120. * @param strings Table of shared strings
  121. */
  122. public XSSFSheetXMLHandler(
  123. StylesTable styles,
  124. ReadOnlySharedStringsTable strings,
  125. SheetContentsHandler sheetContentsHandler,
  126. DataFormatter dataFormatter,
  127. boolean formulasNotResults) {
  128. this(styles, null, strings, sheetContentsHandler, dataFormatter, formulasNotResults);
  129. }
  130. /**
  131. * Accepts objects needed while parsing.
  132. *
  133. * @param styles Table of styles
  134. * @param strings Table of shared strings
  135. */
  136. public XSSFSheetXMLHandler(
  137. StylesTable styles,
  138. ReadOnlySharedStringsTable strings,
  139. SheetContentsHandler sheetContentsHandler,
  140. boolean formulasNotResults) {
  141. this(styles, strings, sheetContentsHandler, new DataFormatter(), formulasNotResults);
  142. }
  143. private void init() {
  144. if (commentsTable != null) {
  145. commentCellRefs = new LinkedList<CellReference>();
  146. List<CTComment> commentList = commentsTable.getCTComments().getCommentList().getCommentList();
  147. for (CTComment comment : commentList) {
  148. commentCellRefs.add(new CellReference(comment.getRef()));
  149. }
  150. }
  151. }
  152. private boolean isTextTag(String name) {
  153. if("v".equals(name)) {
  154. // Easy, normal v text tag
  155. return true;
  156. }
  157. if("inlineStr".equals(name)) {
  158. // Easy inline string
  159. return true;
  160. }
  161. if("t".equals(name) && isIsOpen) {
  162. // Inline string <is><t>...</t></is> pair
  163. return true;
  164. }
  165. // It isn't a text tag
  166. return false;
  167. }
  168. @Override
  169. public void startElement(String uri, String localName, String name,
  170. Attributes attributes) throws SAXException {
  171. if (isTextTag(name)) {
  172. vIsOpen = true;
  173. // Clear contents cache
  174. value.setLength(0);
  175. } else if ("is".equals(name)) {
  176. // Inline string outer tag
  177. isIsOpen = true;
  178. } else if ("f".equals(name)) {
  179. // Clear contents cache
  180. formula.setLength(0);
  181. // Mark us as being a formula if not already
  182. if(nextDataType == xssfDataType.NUMBER) {
  183. nextDataType = xssfDataType.FORMULA;
  184. }
  185. // Decide where to get the formula string from
  186. String type = attributes.getValue("t");
  187. if(type != null && type.equals("shared")) {
  188. // Is it the one that defines the shared, or uses it?
  189. String ref = attributes.getValue("ref");
  190. String si = attributes.getValue("si");
  191. if(ref != null) {
  192. // This one defines it
  193. // TODO Save it somewhere
  194. fIsOpen = true;
  195. } else {
  196. // This one uses a shared formula
  197. // TODO Retrieve the shared formula and tweak it to
  198. // match the current cell
  199. if(formulasNotResults) {
  200. logger.log(POILogger.WARN, "shared formulas not yet supported!");
  201. } else {
  202. // It's a shared formula, so we can't get at the formula string yet
  203. // However, they don't care about the formula string, so that's ok!
  204. }
  205. }
  206. } else {
  207. fIsOpen = true;
  208. }
  209. }
  210. else if("oddHeader".equals(name) || "evenHeader".equals(name) ||
  211. "firstHeader".equals(name) || "firstFooter".equals(name) ||
  212. "oddFooter".equals(name) || "evenFooter".equals(name)) {
  213. hfIsOpen = true;
  214. // Clear contents cache
  215. headerFooter.setLength(0);
  216. }
  217. else if("row".equals(name)) {
  218. rowNum = Integer.parseInt(attributes.getValue("r")) - 1;
  219. output.startRow(rowNum);
  220. }
  221. // c => cell
  222. else if ("c".equals(name)) {
  223. // Set up defaults.
  224. this.nextDataType = xssfDataType.NUMBER;
  225. this.formatIndex = -1;
  226. this.formatString = null;
  227. cellRef = attributes.getValue("r");
  228. String cellType = attributes.getValue("t");
  229. String cellStyleStr = attributes.getValue("s");
  230. if ("b".equals(cellType))
  231. nextDataType = xssfDataType.BOOLEAN;
  232. else if ("e".equals(cellType))
  233. nextDataType = xssfDataType.ERROR;
  234. else if ("inlineStr".equals(cellType))
  235. nextDataType = xssfDataType.INLINE_STRING;
  236. else if ("s".equals(cellType))
  237. nextDataType = xssfDataType.SST_STRING;
  238. else if ("str".equals(cellType))
  239. nextDataType = xssfDataType.FORMULA;
  240. else {
  241. // Number, but almost certainly with a special style or format
  242. XSSFCellStyle style = null;
  243. if (cellStyleStr != null) {
  244. int styleIndex = Integer.parseInt(cellStyleStr);
  245. style = stylesTable.getStyleAt(styleIndex);
  246. } else if (stylesTable.getNumCellStyles() > 0) {
  247. style = stylesTable.getStyleAt(0);
  248. }
  249. if (style != null) {
  250. this.formatIndex = style.getDataFormat();
  251. this.formatString = style.getDataFormatString();
  252. if (this.formatString == null)
  253. this.formatString = BuiltinFormats.getBuiltinFormat(this.formatIndex);
  254. }
  255. }
  256. }
  257. }
  258. @Override
  259. public void endElement(String uri, String localName, String name)
  260. throws SAXException {
  261. String thisStr = null;
  262. // v => contents of a cell
  263. if (isTextTag(name)) {
  264. vIsOpen = false;
  265. // Process the value contents as required, now we have it all
  266. switch (nextDataType) {
  267. case BOOLEAN:
  268. char first = value.charAt(0);
  269. thisStr = first == '0' ? "FALSE" : "TRUE";
  270. break;
  271. case ERROR:
  272. thisStr = "ERROR:" + value.toString();
  273. break;
  274. case FORMULA:
  275. if(formulasNotResults) {
  276. thisStr = formula.toString();
  277. } else {
  278. String fv = value.toString();
  279. if (this.formatString != null) {
  280. try {
  281. // Try to use the value as a formattable number
  282. double d = Double.parseDouble(fv);
  283. thisStr = formatter.formatRawCellContents(d, this.formatIndex, this.formatString);
  284. } catch(NumberFormatException e) {
  285. // Formula is a String result not a Numeric one
  286. thisStr = fv;
  287. }
  288. } else {
  289. // No formating applied, just do raw value in all cases
  290. thisStr = fv;
  291. }
  292. }
  293. break;
  294. case INLINE_STRING:
  295. // TODO: Can these ever have formatting on them?
  296. XSSFRichTextString rtsi = new XSSFRichTextString(value.toString());
  297. thisStr = rtsi.toString();
  298. break;
  299. case SST_STRING:
  300. String sstIndex = value.toString();
  301. try {
  302. int idx = Integer.parseInt(sstIndex);
  303. XSSFRichTextString rtss = new XSSFRichTextString(sharedStringsTable.getEntryAt(idx));
  304. thisStr = rtss.toString();
  305. }
  306. catch (NumberFormatException ex) {
  307. logger.log(POILogger.ERROR, "Failed to parse SST index '" + sstIndex, ex);
  308. }
  309. break;
  310. case NUMBER:
  311. String n = value.toString();
  312. if (this.formatString != null)
  313. thisStr = formatter.formatRawCellContents(Double.parseDouble(n), this.formatIndex, this.formatString);
  314. else
  315. thisStr = n;
  316. break;
  317. default:
  318. thisStr = "(TODO: Unexpected type: " + nextDataType + ")";
  319. break;
  320. }
  321. // Do we have a comment for this cell?
  322. checkForEmptyCellComments(EmptyCellCommentsCheckType.CELL);
  323. XSSFComment comment = commentsTable != null ? commentsTable.findCellComment(cellRef) : null;
  324. // Output
  325. output.cell(cellRef, thisStr, comment);
  326. } else if ("f".equals(name)) {
  327. fIsOpen = false;
  328. } else if ("is".equals(name)) {
  329. isIsOpen = false;
  330. } else if ("row".equals(name)) {
  331. // Handle any "missing" cells which had comments attached
  332. checkForEmptyCellComments(EmptyCellCommentsCheckType.END_OF_ROW);
  333. // Finish up the row
  334. output.endRow(rowNum);
  335. } else if ("sheetData".equals(name)) {
  336. // Handle any "missing" cells which had comments attached
  337. checkForEmptyCellComments(EmptyCellCommentsCheckType.END_OF_SHEET_DATA);
  338. }
  339. else if("oddHeader".equals(name) || "evenHeader".equals(name) ||
  340. "firstHeader".equals(name)) {
  341. hfIsOpen = false;
  342. output.headerFooter(headerFooter.toString(), true, name);
  343. }
  344. else if("oddFooter".equals(name) || "evenFooter".equals(name) ||
  345. "firstFooter".equals(name)) {
  346. hfIsOpen = false;
  347. output.headerFooter(headerFooter.toString(), false, name);
  348. }
  349. }
  350. /**
  351. * Captures characters only if a suitable element is open.
  352. * Originally was just "v"; extended for inlineStr also.
  353. */
  354. @Override
  355. public void characters(char[] ch, int start, int length)
  356. throws SAXException {
  357. if (vIsOpen) {
  358. value.append(ch, start, length);
  359. }
  360. if (fIsOpen) {
  361. formula.append(ch, start, length);
  362. }
  363. if (hfIsOpen) {
  364. headerFooter.append(ch, start, length);
  365. }
  366. }
  367. /**
  368. * Do a check for, and output, comments in otherwise empty cells.
  369. */
  370. private void checkForEmptyCellComments(EmptyCellCommentsCheckType type) {
  371. if (commentCellRefs != null && !commentCellRefs.isEmpty()) {
  372. // If we've reached the end of the sheet data, output any
  373. // comments we haven't yet already handled
  374. if (type == EmptyCellCommentsCheckType.END_OF_SHEET_DATA) {
  375. while (!commentCellRefs.isEmpty()) {
  376. outputEmptyCellComment(commentCellRefs.remove());
  377. }
  378. return;
  379. }
  380. // At the end of a row, handle any comments for "missing" rows before us
  381. if (this.cellRef == null) {
  382. if (type == EmptyCellCommentsCheckType.END_OF_ROW) {
  383. while (!commentCellRefs.isEmpty()) {
  384. if (commentCellRefs.peek().getRow() == rowNum) {
  385. outputEmptyCellComment(commentCellRefs.remove());
  386. } else {
  387. return;
  388. }
  389. }
  390. return;
  391. } else {
  392. throw new IllegalStateException("Cell ref should be null only if there are only empty cells in the row; rowNum: " + rowNum);
  393. }
  394. }
  395. CellReference nextCommentCellRef;
  396. do {
  397. CellReference cellRef = new CellReference(this.cellRef);
  398. CellReference peekCellRef = commentCellRefs.peek();
  399. if (type == EmptyCellCommentsCheckType.CELL && cellRef.equals(peekCellRef)) {
  400. // remove the comment cell ref from the list if we're about to handle it alongside the cell content
  401. commentCellRefs.remove();
  402. return;
  403. } else {
  404. // fill in any gaps if there are empty cells with comment mixed in with non-empty cells
  405. int comparison = cellRefComparator.compare(peekCellRef, cellRef);
  406. if (comparison > 0 && type == EmptyCellCommentsCheckType.END_OF_ROW && peekCellRef.getRow() <= rowNum) {
  407. nextCommentCellRef = commentCellRefs.remove();
  408. outputEmptyCellComment(nextCommentCellRef);
  409. } else if (comparison < 0 && type == EmptyCellCommentsCheckType.CELL && peekCellRef.getRow() <= rowNum) {
  410. nextCommentCellRef = commentCellRefs.remove();
  411. outputEmptyCellComment(nextCommentCellRef);
  412. } else {
  413. nextCommentCellRef = null;
  414. }
  415. }
  416. } while (nextCommentCellRef != null && !commentCellRefs.isEmpty());
  417. }
  418. }
  419. /**
  420. * Output an empty-cell comment.
  421. */
  422. private void outputEmptyCellComment(CellReference cellRef) {
  423. String cellRefString = cellRef.formatAsString();
  424. XSSFComment comment = commentsTable.findCellComment(cellRefString);
  425. output.emptyCellComment(cellRefString, comment);
  426. }
  427. private enum EmptyCellCommentsCheckType {
  428. CELL,
  429. END_OF_ROW,
  430. END_OF_SHEET_DATA
  431. }
  432. private static final Comparator<CellReference> cellRefComparator = new Comparator<CellReference>() {
  433. @Override
  434. public int compare(CellReference o1, CellReference o2) {
  435. int result = compare(o1.getRow(), o2.getRow());
  436. if (result == 0) {
  437. result = compare(o1.getCol(), o2.getCol());
  438. }
  439. return result;
  440. }
  441. public int compare(int x, int y) {
  442. return (x < y) ? -1 : ((x == y) ? 0 : 1);
  443. }
  444. };
  445. /**
  446. * You need to implement this to handle the results
  447. * of the sheet parsing.
  448. */
  449. public interface SheetContentsHandler {
  450. /** A row with the (zero based) row number has started */
  451. public void startRow(int rowNum);
  452. /** A row with the (zero based) row number has ended */
  453. public void endRow(int rowNum);
  454. /** A cell, with the given formatted value, and possibly a comment, was encountered */
  455. public void cell(String cellReference, String formattedValue, XSSFComment comment);
  456. /** A comment for an otherwise-empty cell was encountered */
  457. public void emptyCellComment(String cellReference, XSSFComment comment);
  458. /** A header or footer has been encountered */
  459. public void headerFooter(String text, boolean isHeader, String tagName);
  460. }
  461. }