Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

XSSFSheetXMLHandler.java 20KB

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