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.

XSSFCell.java 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  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.usermodel;
  16. import java.text.DateFormat;
  17. import java.text.SimpleDateFormat;
  18. import java.util.Calendar;
  19. import java.util.Date;
  20. import org.apache.poi.ss.formula.ptg.Ptg;
  21. import org.apache.poi.ss.formula.SharedFormula;
  22. import org.apache.poi.ss.formula.eval.ErrorEval;
  23. import org.apache.poi.ss.SpreadsheetVersion;
  24. import org.apache.poi.ss.formula.FormulaParser;
  25. import org.apache.poi.ss.formula.FormulaRenderer;
  26. import org.apache.poi.ss.formula.FormulaType;
  27. import org.apache.poi.ss.usermodel.Cell;
  28. import org.apache.poi.ss.usermodel.CellStyle;
  29. import org.apache.poi.ss.usermodel.Comment;
  30. import org.apache.poi.ss.usermodel.DataFormatter;
  31. import org.apache.poi.ss.usermodel.DateUtil;
  32. import org.apache.poi.ss.usermodel.FormulaError;
  33. import org.apache.poi.ss.usermodel.Hyperlink;
  34. import org.apache.poi.ss.usermodel.RichTextString;
  35. import org.apache.poi.ss.util.CellRangeAddress;
  36. import org.apache.poi.ss.util.CellReference;
  37. import org.apache.poi.xssf.model.SharedStringsTable;
  38. import org.apache.poi.xssf.model.StylesTable;
  39. import org.apache.poi.util.Internal;
  40. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;
  41. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellFormula;
  42. import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellFormulaType;
  43. import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType;
  44. /**
  45. * High level representation of a cell in a row of a spreadsheet.
  46. * <p>
  47. * Cells can be numeric, formula-based or string-based (text). The cell type
  48. * specifies this. String cells cannot conatin numbers and numeric cells cannot
  49. * contain strings (at least according to our model). Client apps should do the
  50. * conversions themselves. Formula cells have the formula string, as well as
  51. * the formula result, which can be numeric or string.
  52. * </p>
  53. * <p>
  54. * Cells should have their number (0 based) before being added to a row. Only
  55. * cells that have values should be added.
  56. * </p>
  57. */
  58. public final class XSSFCell implements Cell {
  59. private static final String FALSE_AS_STRING = "0";
  60. private static final String TRUE_AS_STRING = "1";
  61. /**
  62. * the xml bean containing information about the cell's location, value,
  63. * data type, formatting, and formula
  64. */
  65. private final CTCell _cell;
  66. /**
  67. * the XSSFRow this cell belongs to
  68. */
  69. private final XSSFRow _row;
  70. /**
  71. * 0-based column index
  72. */
  73. private int _cellNum;
  74. /**
  75. * Table of strings shared across this workbook.
  76. * If two cells contain the same string, then the cell value is the same index into SharedStringsTable
  77. */
  78. private SharedStringsTable _sharedStringSource;
  79. /**
  80. * Table of cell styles shared across all cells in a workbook.
  81. */
  82. private StylesTable _stylesSource;
  83. /**
  84. * Construct a XSSFCell.
  85. *
  86. * @param row the parent row.
  87. * @param cell the xml bean containing information about the cell.
  88. */
  89. protected XSSFCell(XSSFRow row, CTCell cell) {
  90. _cell = cell;
  91. _row = row;
  92. if (cell.getR() != null) {
  93. _cellNum = new CellReference(cell.getR()).getCol();
  94. }
  95. _sharedStringSource = row.getSheet().getWorkbook().getSharedStringSource();
  96. _stylesSource = row.getSheet().getWorkbook().getStylesSource();
  97. }
  98. /**
  99. * @return table of strings shared across this workbook
  100. */
  101. protected SharedStringsTable getSharedStringSource() {
  102. return _sharedStringSource;
  103. }
  104. /**
  105. * @return table of cell styles shared across this workbook
  106. */
  107. protected StylesTable getStylesSource() {
  108. return _stylesSource;
  109. }
  110. /**
  111. * Returns the sheet this cell belongs to
  112. *
  113. * @return the sheet this cell belongs to
  114. */
  115. public XSSFSheet getSheet() {
  116. return getRow().getSheet();
  117. }
  118. /**
  119. * Returns the row this cell belongs to
  120. *
  121. * @return the row this cell belongs to
  122. */
  123. public XSSFRow getRow() {
  124. return _row;
  125. }
  126. /**
  127. * Get the value of the cell as a boolean.
  128. * <p>
  129. * For strings, numbers, and errors, we throw an exception. For blank cells we return a false.
  130. * </p>
  131. * @return the value of the cell as a boolean
  132. * @throws IllegalStateException if the cell type returned by {@link #getCellType()}
  133. * is not CELL_TYPE_BOOLEAN, CELL_TYPE_BLANK or CELL_TYPE_FORMULA
  134. */
  135. public boolean getBooleanCellValue() {
  136. int cellType = getCellType();
  137. switch(cellType) {
  138. case CELL_TYPE_BLANK:
  139. return false;
  140. case CELL_TYPE_BOOLEAN:
  141. return _cell.isSetV() && TRUE_AS_STRING.equals(_cell.getV());
  142. case CELL_TYPE_FORMULA:
  143. //YK: should throw an exception if requesting boolean value from a non-boolean formula
  144. return _cell.isSetV() && TRUE_AS_STRING.equals(_cell.getV());
  145. default:
  146. throw typeMismatch(CELL_TYPE_BOOLEAN, cellType, false);
  147. }
  148. }
  149. /**
  150. * Set a boolean value for the cell
  151. *
  152. * @param value the boolean value to set this cell to. For formulas we'll set the
  153. * precalculated value, for booleans we'll set its value. For other types we
  154. * will change the cell to a boolean cell and set its value.
  155. */
  156. public void setCellValue(boolean value) {
  157. _cell.setT(STCellType.B);
  158. _cell.setV(value ? TRUE_AS_STRING : FALSE_AS_STRING);
  159. }
  160. /**
  161. * Get the value of the cell as a number.
  162. * <p>
  163. * For strings we throw an exception. For blank cells we return a 0.
  164. * For formulas or error cells we return the precalculated value;
  165. * </p>
  166. * @return the value of the cell as a number
  167. * @throws IllegalStateException if the cell type returned by {@link #getCellType()} is CELL_TYPE_STRING
  168. * @exception NumberFormatException if the cell value isn't a parsable <code>double</code>.
  169. * @see DataFormatter for turning this number into a string similar to that which Excel would render this number as.
  170. */
  171. public double getNumericCellValue() {
  172. int cellType = getCellType();
  173. switch(cellType) {
  174. case CELL_TYPE_BLANK:
  175. return 0.0;
  176. case CELL_TYPE_FORMULA:
  177. case CELL_TYPE_NUMERIC:
  178. if(_cell.isSetV()) {
  179. try {
  180. return Double.parseDouble(_cell.getV());
  181. } catch(NumberFormatException e) {
  182. throw typeMismatch(CELL_TYPE_NUMERIC, CELL_TYPE_STRING, false);
  183. }
  184. } else {
  185. return 0.0;
  186. }
  187. default:
  188. throw typeMismatch(CELL_TYPE_NUMERIC, cellType, false);
  189. }
  190. }
  191. /**
  192. * Set a numeric value for the cell
  193. *
  194. * @param value the numeric value to set this cell to. For formulas we'll set the
  195. * precalculated value, for numerics we'll set its value. For other types we
  196. * will change the cell to a numeric cell and set its value.
  197. */
  198. public void setCellValue(double value) {
  199. if(Double.isInfinite(value)) {
  200. // Excel does not support positive/negative infinities,
  201. // rather, it gives a #DIV/0! error in these cases.
  202. _cell.setT(STCellType.E);
  203. _cell.setV(FormulaError.DIV0.getString());
  204. } else if (Double.isNaN(value)){
  205. // Excel does not support Not-a-Number (NaN),
  206. // instead it immediately generates an #NUM! error.
  207. _cell.setT(STCellType.E);
  208. _cell.setV(FormulaError.NUM.getString());
  209. } else {
  210. _cell.setT(STCellType.N);
  211. _cell.setV(String.valueOf(value));
  212. }
  213. }
  214. /**
  215. * Get the value of the cell as a string
  216. * <p>
  217. * For numeric cells we throw an exception. For blank cells we return an empty string.
  218. * For formulaCells that are not string Formulas, we throw an exception
  219. * </p>
  220. * @return the value of the cell as a string
  221. */
  222. public String getStringCellValue() {
  223. XSSFRichTextString str = getRichStringCellValue();
  224. return str == null ? null : str.getString();
  225. }
  226. /**
  227. * Get the value of the cell as a XSSFRichTextString
  228. * <p>
  229. * For numeric cells we throw an exception. For blank cells we return an empty string.
  230. * For formula cells we return the pre-calculated value if a string, otherwise an exception
  231. * </p>
  232. * @return the value of the cell as a XSSFRichTextString
  233. */
  234. public XSSFRichTextString getRichStringCellValue() {
  235. int cellType = getCellType();
  236. XSSFRichTextString rt;
  237. switch (cellType) {
  238. case CELL_TYPE_BLANK:
  239. rt = new XSSFRichTextString("");
  240. break;
  241. case CELL_TYPE_STRING:
  242. if (_cell.getT() == STCellType.INLINE_STR) {
  243. if(_cell.isSetIs()) {
  244. //string is expressed directly in the cell definition instead of implementing the shared string table.
  245. rt = new XSSFRichTextString(_cell.getIs());
  246. } else if (_cell.isSetV()) {
  247. //cached result of a formula
  248. rt = new XSSFRichTextString(_cell.getV());
  249. } else {
  250. rt = new XSSFRichTextString("");
  251. }
  252. } else if (_cell.getT() == STCellType.STR) {
  253. //cached formula value
  254. rt = new XSSFRichTextString(_cell.isSetV() ? _cell.getV() : "");
  255. } else {
  256. if (_cell.isSetV()) {
  257. int idx = Integer.parseInt(_cell.getV());
  258. rt = new XSSFRichTextString(_sharedStringSource.getEntryAt(idx));
  259. }
  260. else {
  261. rt = new XSSFRichTextString("");
  262. }
  263. }
  264. break;
  265. case CELL_TYPE_FORMULA:
  266. checkFormulaCachedValueType(CELL_TYPE_STRING, getBaseCellType(false));
  267. rt = new XSSFRichTextString(_cell.isSetV() ? _cell.getV() : "");
  268. break;
  269. default:
  270. throw typeMismatch(CELL_TYPE_STRING, cellType, false);
  271. }
  272. rt.setStylesTableReference(_stylesSource);
  273. return rt;
  274. }
  275. private static void checkFormulaCachedValueType(int expectedTypeCode, int cachedValueType) {
  276. if (cachedValueType != expectedTypeCode) {
  277. throw typeMismatch(expectedTypeCode, cachedValueType, true);
  278. }
  279. }
  280. /**
  281. * Set a string value for the cell.
  282. *
  283. * @param str value to set the cell to. For formulas we'll set the formula
  284. * cached string result, for String cells we'll set its value. For other types we will
  285. * change the cell to a string cell and set its value.
  286. * If value is null then we will change the cell to a Blank cell.
  287. */
  288. public void setCellValue(String str) {
  289. setCellValue(str == null ? null : new XSSFRichTextString(str));
  290. }
  291. /**
  292. * Set a string value for the cell.
  293. *
  294. * @param str value to set the cell to. For formulas we'll set the 'pre-evaluated result string,
  295. * for String cells we'll set its value. For other types we will
  296. * change the cell to a string cell and set its value.
  297. * If value is null then we will change the cell to a Blank cell.
  298. */
  299. public void setCellValue(RichTextString str) {
  300. if(str == null || str.getString() == null){
  301. setCellType(Cell.CELL_TYPE_BLANK);
  302. return;
  303. }
  304. int cellType = getCellType();
  305. switch(cellType){
  306. case Cell.CELL_TYPE_FORMULA:
  307. _cell.setV(str.getString());
  308. _cell.setT(STCellType.STR);
  309. break;
  310. default:
  311. if(_cell.getT() == STCellType.INLINE_STR) {
  312. //set the 'pre-evaluated result
  313. _cell.setV(str.getString());
  314. } else {
  315. _cell.setT(STCellType.S);
  316. XSSFRichTextString rt = (XSSFRichTextString)str;
  317. rt.setStylesTableReference(_stylesSource);
  318. int sRef = _sharedStringSource.addEntry(rt.getCTRst());
  319. _cell.setV(Integer.toString(sRef));
  320. }
  321. break;
  322. }
  323. }
  324. /**
  325. * Return a formula for the cell, for example, <code>SUM(C4:E4)</code>
  326. *
  327. * @return a formula for the cell
  328. * @throws IllegalStateException if the cell type returned by {@link #getCellType()} is not CELL_TYPE_FORMULA
  329. */
  330. public String getCellFormula() {
  331. int cellType = getCellType();
  332. if(cellType != CELL_TYPE_FORMULA) throw typeMismatch(CELL_TYPE_FORMULA, cellType, false);
  333. CTCellFormula f = _cell.getF();
  334. if (isPartOfArrayFormulaGroup() && f == null) {
  335. XSSFCell cell = getSheet().getFirstCellInArrayFormula(this);
  336. return cell.getCellFormula();
  337. }
  338. if (f.getT() == STCellFormulaType.SHARED) {
  339. return convertSharedFormula((int)f.getSi());
  340. }
  341. return f.getStringValue();
  342. }
  343. /**
  344. * Creates a non shared formula from the shared formula counterpart
  345. *
  346. * @param si Shared Group Index
  347. * @return non shared formula created for the given shared formula and this cell
  348. */
  349. private String convertSharedFormula(int si){
  350. XSSFSheet sheet = getSheet();
  351. CTCellFormula f = sheet.getSharedFormula(si);
  352. if(f == null) throw new IllegalStateException(
  353. "Master cell of a shared formula with sid="+si+" was not found");
  354. String sharedFormula = f.getStringValue();
  355. //Range of cells which the shared formula applies to
  356. String sharedFormulaRange = f.getRef();
  357. CellRangeAddress ref = CellRangeAddress.valueOf(sharedFormulaRange);
  358. int sheetIndex = sheet.getWorkbook().getSheetIndex(sheet);
  359. XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(sheet.getWorkbook());
  360. SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL2007);
  361. Ptg[] ptgs = FormulaParser.parse(sharedFormula, fpb, FormulaType.CELL, sheetIndex);
  362. Ptg[] fmla = sf.convertSharedFormulas(ptgs,
  363. getRowIndex() - ref.getFirstRow(), getColumnIndex() - ref.getFirstColumn());
  364. return FormulaRenderer.toFormulaString(fpb, fmla);
  365. }
  366. /**
  367. * Sets formula for this cell.
  368. * <p>
  369. * Note, this method only sets the formula string and does not calculate the formula value.
  370. * To set the precalculated value use {@link #setCellValue(double)} or {@link #setCellValue(String)}
  371. * </p>
  372. *
  373. * @param formula the formula to set, e.g. <code>"SUM(C4:E4)"</code>.
  374. * If the argument is <code>null</code> then the current formula is removed.
  375. * @throws org.apache.poi.ss.formula.FormulaParseException if the formula has incorrect syntax or is otherwise invalid
  376. * @throws IllegalStateException if the operation is not allowed, for example,
  377. * when the cell is a part of a multi-cell array formula
  378. */
  379. public void setCellFormula(String formula) {
  380. if(isPartOfArrayFormulaGroup()){
  381. notifyArrayFormulaChanging();
  382. }
  383. setFormula(formula, FormulaType.CELL);
  384. }
  385. /* package */ void setCellArrayFormula(String formula, CellRangeAddress range) {
  386. setFormula(formula, FormulaType.ARRAY);
  387. CTCellFormula cellFormula = _cell.getF();
  388. cellFormula.setT(STCellFormulaType.ARRAY);
  389. cellFormula.setRef(range.formatAsString());
  390. }
  391. private void setFormula(String formula, int formulaType) {
  392. XSSFWorkbook wb = _row.getSheet().getWorkbook();
  393. if (formula == null) {
  394. wb.onDeleteFormula(this);
  395. if(_cell.isSetF()) _cell.unsetF();
  396. return;
  397. }
  398. XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb);
  399. //validate through the FormulaParser
  400. FormulaParser.parse(formula, fpb, formulaType, wb.getSheetIndex(getSheet()));
  401. CTCellFormula f = CTCellFormula.Factory.newInstance();
  402. f.setStringValue(formula);
  403. _cell.setF(f);
  404. if(_cell.isSetV()) _cell.unsetV();
  405. }
  406. /**
  407. * Returns column index of this cell
  408. *
  409. * @return zero-based column index of a column in a sheet.
  410. */
  411. public int getColumnIndex() {
  412. return this._cellNum;
  413. }
  414. /**
  415. * Returns row index of a row in the sheet that contains this cell
  416. *
  417. * @return zero-based row index of a row in the sheet that contains this cell
  418. */
  419. public int getRowIndex() {
  420. return _row.getRowNum();
  421. }
  422. /**
  423. * Returns an A1 style reference to the location of this cell
  424. *
  425. * @return A1 style reference to the location of this cell
  426. */
  427. public String getReference() {
  428. return _cell.getR();
  429. }
  430. /**
  431. * Return the cell's style.
  432. *
  433. * @return the cell's style.</code>
  434. */
  435. public XSSFCellStyle getCellStyle() {
  436. XSSFCellStyle style = null;
  437. if(_stylesSource.getNumCellStyles() > 0){
  438. long idx = _cell.isSetS() ? _cell.getS() : 0;
  439. style = _stylesSource.getStyleAt((int)idx);
  440. }
  441. return style;
  442. }
  443. /**
  444. * Set the style for the cell. The style should be an XSSFCellStyle created/retreived from
  445. * the XSSFWorkbook.
  446. *
  447. * @param style reference contained in the workbook.
  448. * If the value is null then the style information is removed causing the cell to used the default workbook style.
  449. */
  450. public void setCellStyle(CellStyle style) {
  451. if(style == null) {
  452. if(_cell.isSetS()) _cell.unsetS();
  453. } else {
  454. XSSFCellStyle xStyle = (XSSFCellStyle)style;
  455. xStyle.verifyBelongsToStylesSource(_stylesSource);
  456. long idx = _stylesSource.putStyle(xStyle);
  457. _cell.setS(idx);
  458. }
  459. }
  460. /**
  461. * Return the cell type.
  462. *
  463. * @return the cell type
  464. * @see Cell#CELL_TYPE_BLANK
  465. * @see Cell#CELL_TYPE_NUMERIC
  466. * @see Cell#CELL_TYPE_STRING
  467. * @see Cell#CELL_TYPE_FORMULA
  468. * @see Cell#CELL_TYPE_BOOLEAN
  469. * @see Cell#CELL_TYPE_ERROR
  470. */
  471. public int getCellType() {
  472. if (_cell.getF() != null || getSheet().isCellInArrayFormulaContext(this)) {
  473. return CELL_TYPE_FORMULA;
  474. }
  475. return getBaseCellType(true);
  476. }
  477. /**
  478. * Only valid for formula cells
  479. * @return one of ({@link #CELL_TYPE_NUMERIC}, {@link #CELL_TYPE_STRING},
  480. * {@link #CELL_TYPE_BOOLEAN}, {@link #CELL_TYPE_ERROR}) depending
  481. * on the cached value of the formula
  482. */
  483. public int getCachedFormulaResultType() {
  484. if (_cell.getF() == null) {
  485. throw new IllegalStateException("Only formula cells have cached results");
  486. }
  487. return getBaseCellType(false);
  488. }
  489. /**
  490. * Detect cell type based on the "t" attribute of the CTCell bean
  491. */
  492. private int getBaseCellType(boolean blankCells) {
  493. switch (_cell.getT().intValue()) {
  494. case STCellType.INT_B:
  495. return CELL_TYPE_BOOLEAN;
  496. case STCellType.INT_N:
  497. if (!_cell.isSetV() && blankCells) {
  498. // ooxml does have a separate cell type of 'blank'. A blank cell gets encoded as
  499. // (either not present or) a numeric cell with no value set.
  500. // The formula evaluator (and perhaps other clients of this interface) needs to
  501. // distinguish blank values which sometimes get translated into zero and sometimes
  502. // empty string, depending on context
  503. return CELL_TYPE_BLANK;
  504. }
  505. return CELL_TYPE_NUMERIC;
  506. case STCellType.INT_E:
  507. return CELL_TYPE_ERROR;
  508. case STCellType.INT_S: // String is in shared strings
  509. case STCellType.INT_INLINE_STR: // String is inline in cell
  510. case STCellType.INT_STR:
  511. return CELL_TYPE_STRING;
  512. default:
  513. throw new IllegalStateException("Illegal cell type: " + this._cell.getT());
  514. }
  515. }
  516. /**
  517. * Get the value of the cell as a date.
  518. * <p>
  519. * For strings we throw an exception. For blank cells we return a null.
  520. * </p>
  521. * @return the value of the cell as a date
  522. * @throws IllegalStateException if the cell type returned by {@link #getCellType()} is CELL_TYPE_STRING
  523. * @exception NumberFormatException if the cell value isn't a parsable <code>double</code>.
  524. * @see DataFormatter for formatting this date into a string similar to how excel does.
  525. */
  526. public Date getDateCellValue() {
  527. int cellType = getCellType();
  528. if (cellType == CELL_TYPE_BLANK) {
  529. return null;
  530. }
  531. double value = getNumericCellValue();
  532. boolean date1904 = getSheet().getWorkbook().isDate1904();
  533. return DateUtil.getJavaDate(value, date1904);
  534. }
  535. /**
  536. * Set a date value for the cell. Excel treats dates as numeric so you will need to format the cell as
  537. * a date.
  538. *
  539. * @param value the date value to set this cell to. For formulas we'll set the
  540. * precalculated value, for numerics we'll set its value. For other types we
  541. * will change the cell to a numeric cell and set its value.
  542. */
  543. public void setCellValue(Date value) {
  544. boolean date1904 = getSheet().getWorkbook().isDate1904();
  545. setCellValue(DateUtil.getExcelDate(value, date1904));
  546. }
  547. /**
  548. * Set a date value for the cell. Excel treats dates as numeric so you will need to format the cell as
  549. * a date.
  550. * <p>
  551. * This will set the cell value based on the Calendar's timezone. As Excel
  552. * does not support timezones this means that both 20:00+03:00 and
  553. * 20:00-03:00 will be reported as the same value (20:00) even that there
  554. * are 6 hours difference between the two times. This difference can be
  555. * preserved by using <code>setCellValue(value.getTime())</code> which will
  556. * automatically shift the times to the default timezone.
  557. * </p>
  558. *
  559. * @param value the date value to set this cell to. For formulas we'll set the
  560. * precalculated value, for numerics we'll set its value. For othertypes we
  561. * will change the cell to a numeric cell and set its value.
  562. */
  563. public void setCellValue(Calendar value) {
  564. boolean date1904 = getSheet().getWorkbook().isDate1904();
  565. setCellValue( DateUtil.getExcelDate(value, date1904 ));
  566. }
  567. /**
  568. * Returns the error message, such as #VALUE!
  569. *
  570. * @return the error message such as #VALUE!
  571. * @throws IllegalStateException if the cell type returned by {@link #getCellType()} isn't CELL_TYPE_ERROR
  572. * @see FormulaError
  573. */
  574. public String getErrorCellString() {
  575. int cellType = getBaseCellType(true);
  576. if(cellType != CELL_TYPE_ERROR) throw typeMismatch(CELL_TYPE_ERROR, cellType, false);
  577. return _cell.getV();
  578. }
  579. /**
  580. * Get the value of the cell as an error code.
  581. * <p>
  582. * For strings, numbers, and booleans, we throw an exception.
  583. * For blank cells we return a 0.
  584. * </p>
  585. *
  586. * @return the value of the cell as an error code
  587. * @throws IllegalStateException if the cell type returned by {@link #getCellType()} isn't CELL_TYPE_ERROR
  588. * @see FormulaError
  589. */
  590. public byte getErrorCellValue() {
  591. String code = getErrorCellString();
  592. if (code == null) {
  593. return 0;
  594. }
  595. return FormulaError.forString(code).getCode();
  596. }
  597. /**
  598. * Set a error value for the cell
  599. *
  600. * @param errorCode the error value to set this cell to. For formulas we'll set the
  601. * precalculated value , for errors we'll set
  602. * its value. For other types we will change the cell to an error
  603. * cell and set its value.
  604. * @see FormulaError
  605. */
  606. public void setCellErrorValue(byte errorCode) {
  607. FormulaError error = FormulaError.forInt(errorCode);
  608. setCellErrorValue(error);
  609. }
  610. /**
  611. * Set a error value for the cell
  612. *
  613. * @param error the error value to set this cell to. For formulas we'll set the
  614. * precalculated value , for errors we'll set
  615. * its value. For other types we will change the cell to an error
  616. * cell and set its value.
  617. */
  618. public void setCellErrorValue(FormulaError error) {
  619. _cell.setT(STCellType.E);
  620. _cell.setV(error.getString());
  621. }
  622. /**
  623. * Sets this cell as the active cell for the worksheet.
  624. */
  625. public void setAsActiveCell() {
  626. getSheet().setActiveCell(_cell.getR());
  627. }
  628. /**
  629. * Blanks this cell. Blank cells have no formula or value but may have styling.
  630. * This method erases all the data previously associated with this cell.
  631. */
  632. private void setBlank(){
  633. CTCell blank = CTCell.Factory.newInstance();
  634. blank.setR(_cell.getR());
  635. if(_cell.isSetS()) blank.setS(_cell.getS());
  636. _cell.set(blank);
  637. }
  638. /**
  639. * Sets column index of this cell
  640. *
  641. * @param num column index of this cell
  642. */
  643. protected void setCellNum(int num) {
  644. checkBounds(num);
  645. _cellNum = num;
  646. String ref = new CellReference(getRowIndex(), getColumnIndex()).formatAsString();
  647. _cell.setR(ref);
  648. }
  649. /**
  650. * Set the cells type (numeric, formula or string)
  651. *
  652. * @throws IllegalArgumentException if the specified cell type is invalid
  653. * @see #CELL_TYPE_NUMERIC
  654. * @see #CELL_TYPE_STRING
  655. * @see #CELL_TYPE_FORMULA
  656. * @see #CELL_TYPE_BLANK
  657. * @see #CELL_TYPE_BOOLEAN
  658. * @see #CELL_TYPE_ERROR
  659. */
  660. public void setCellType(int cellType) {
  661. int prevType = getCellType();
  662. if(isPartOfArrayFormulaGroup()){
  663. notifyArrayFormulaChanging();
  664. }
  665. if(prevType == CELL_TYPE_FORMULA && cellType != CELL_TYPE_FORMULA) {
  666. getSheet().getWorkbook().onDeleteFormula(this);
  667. }
  668. switch (cellType) {
  669. case CELL_TYPE_BLANK:
  670. setBlank();
  671. break;
  672. case CELL_TYPE_BOOLEAN:
  673. String newVal = convertCellValueToBoolean() ? TRUE_AS_STRING : FALSE_AS_STRING;
  674. _cell.setT(STCellType.B);
  675. _cell.setV(newVal);
  676. break;
  677. case CELL_TYPE_NUMERIC:
  678. _cell.setT(STCellType.N);
  679. break;
  680. case CELL_TYPE_ERROR:
  681. _cell.setT(STCellType.E);
  682. break;
  683. case CELL_TYPE_STRING:
  684. if(prevType != CELL_TYPE_STRING){
  685. String str = convertCellValueToString();
  686. XSSFRichTextString rt = new XSSFRichTextString(str);
  687. rt.setStylesTableReference(_stylesSource);
  688. int sRef = _sharedStringSource.addEntry(rt.getCTRst());
  689. _cell.setV(Integer.toString(sRef));
  690. }
  691. _cell.setT(STCellType.S);
  692. break;
  693. case CELL_TYPE_FORMULA:
  694. if(!_cell.isSetF()){
  695. CTCellFormula f = CTCellFormula.Factory.newInstance();
  696. f.setStringValue("0");
  697. _cell.setF(f);
  698. if(_cell.isSetT()) _cell.unsetT();
  699. }
  700. break;
  701. default:
  702. throw new IllegalArgumentException("Illegal cell type: " + cellType);
  703. }
  704. if (cellType != CELL_TYPE_FORMULA && _cell.isSetF()) {
  705. _cell.unsetF();
  706. }
  707. }
  708. /**
  709. * Returns a string representation of the cell
  710. * <p>
  711. * Formula cells return the formula string, rather than the formula result.
  712. * Dates are displayed in dd-MMM-yyyy format
  713. * Errors are displayed as #ERR&lt;errIdx&gt;
  714. * </p>
  715. */
  716. public String toString() {
  717. switch (getCellType()) {
  718. case CELL_TYPE_BLANK:
  719. return "";
  720. case CELL_TYPE_BOOLEAN:
  721. return getBooleanCellValue() ? "TRUE" : "FALSE";
  722. case CELL_TYPE_ERROR:
  723. return ErrorEval.getText(getErrorCellValue());
  724. case CELL_TYPE_FORMULA:
  725. return getCellFormula();
  726. case CELL_TYPE_NUMERIC:
  727. if (DateUtil.isCellDateFormatted(this)) {
  728. DateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
  729. return sdf.format(getDateCellValue());
  730. }
  731. return getNumericCellValue() + "";
  732. case CELL_TYPE_STRING:
  733. return getRichStringCellValue().toString();
  734. default:
  735. return "Unknown Cell Type: " + getCellType();
  736. }
  737. }
  738. /**
  739. * Returns the raw, underlying ooxml value for the cell
  740. * <p>
  741. * If the cell contains a string, then this value is an index into
  742. * the shared string table, pointing to the actual string value. Otherwise,
  743. * the value of the cell is expressed directly in this element. Cells containing formulas express
  744. * the last calculated result of the formula in this element.
  745. * </p>
  746. *
  747. * @return the raw cell value as contained in the underlying CTCell bean,
  748. * <code>null</code> for blank cells.
  749. */
  750. public String getRawValue() {
  751. return _cell.getV();
  752. }
  753. /**
  754. * Used to help format error messages
  755. */
  756. private static String getCellTypeName(int cellTypeCode) {
  757. switch (cellTypeCode) {
  758. case CELL_TYPE_BLANK: return "blank";
  759. case CELL_TYPE_STRING: return "text";
  760. case CELL_TYPE_BOOLEAN: return "boolean";
  761. case CELL_TYPE_ERROR: return "error";
  762. case CELL_TYPE_NUMERIC: return "numeric";
  763. case CELL_TYPE_FORMULA: return "formula";
  764. }
  765. return "#unknown cell type (" + cellTypeCode + ")#";
  766. }
  767. /**
  768. * Used to help format error messages
  769. */
  770. private static RuntimeException typeMismatch(int expectedTypeCode, int actualTypeCode, boolean isFormulaCell) {
  771. String msg = "Cannot get a "
  772. + getCellTypeName(expectedTypeCode) + " value from a "
  773. + getCellTypeName(actualTypeCode) + " " + (isFormulaCell ? "formula " : "") + "cell";
  774. return new IllegalStateException(msg);
  775. }
  776. /**
  777. * @throws RuntimeException if the bounds are exceeded.
  778. */
  779. private static void checkBounds(int cellIndex) {
  780. SpreadsheetVersion v = SpreadsheetVersion.EXCEL2007;
  781. int maxcol = SpreadsheetVersion.EXCEL2007.getLastColumnIndex();
  782. if (cellIndex < 0 || cellIndex > maxcol) {
  783. throw new IllegalArgumentException("Invalid column index (" + cellIndex
  784. + "). Allowable column range for " + v.name() + " is (0.."
  785. + maxcol + ") or ('A'..'" + v.getLastColumnName() + "')");
  786. }
  787. }
  788. /**
  789. * Returns cell comment associated with this cell
  790. *
  791. * @return the cell comment associated with this cell or <code>null</code>
  792. */
  793. public XSSFComment getCellComment() {
  794. return getSheet().getCellComment(_row.getRowNum(), getColumnIndex());
  795. }
  796. /**
  797. * Assign a comment to this cell. If the supplied comment is null,
  798. * the comment for this cell will be removed.
  799. *
  800. * @param comment the XSSFComment associated with this cell
  801. */
  802. public void setCellComment(Comment comment) {
  803. if(comment == null) {
  804. removeCellComment();
  805. return;
  806. }
  807. comment.setRow(getRowIndex());
  808. comment.setColumn(getColumnIndex());
  809. }
  810. /**
  811. * Removes the comment for this cell, if there is one.
  812. */
  813. public void removeCellComment() {
  814. XSSFComment comment = getCellComment();
  815. if(comment != null){
  816. String ref = _cell.getR();
  817. XSSFSheet sh = getSheet();
  818. sh.getCommentsTable(false).removeComment(ref);
  819. sh.getVMLDrawing(false).removeCommentShape(getRowIndex(), getColumnIndex());
  820. }
  821. }
  822. /**
  823. * Returns hyperlink associated with this cell
  824. *
  825. * @return hyperlink associated with this cell or <code>null</code> if not found
  826. */
  827. public XSSFHyperlink getHyperlink() {
  828. return getSheet().getHyperlink(_row.getRowNum(), _cellNum);
  829. }
  830. /**
  831. * Assign a hyperlink to this cell
  832. *
  833. * @param hyperlink the hyperlink to associate with this cell
  834. */
  835. public void setHyperlink(Hyperlink hyperlink) {
  836. XSSFHyperlink link = (XSSFHyperlink)hyperlink;
  837. // Assign to us
  838. link.setCellReference( new CellReference(_row.getRowNum(), _cellNum).formatAsString() );
  839. // Add to the lists
  840. getSheet().addHyperlink(link);
  841. }
  842. /**
  843. * Returns the xml bean containing information about the cell's location (reference), value,
  844. * data type, formatting, and formula
  845. *
  846. * @return the xml bean containing information about this cell
  847. */
  848. @Internal
  849. public CTCell getCTCell(){
  850. return _cell;
  851. }
  852. /**
  853. * Chooses a new boolean value for the cell when its type is changing.<p/>
  854. *
  855. * Usually the caller is calling setCellType() with the intention of calling
  856. * setCellValue(boolean) straight afterwards. This method only exists to give
  857. * the cell a somewhat reasonable value until the setCellValue() call (if at all).
  858. * TODO - perhaps a method like setCellTypeAndValue(int, Object) should be introduced to avoid this
  859. */
  860. private boolean convertCellValueToBoolean() {
  861. int cellType = getCellType();
  862. if (cellType == CELL_TYPE_FORMULA) {
  863. cellType = getBaseCellType(false);
  864. }
  865. switch (cellType) {
  866. case CELL_TYPE_BOOLEAN:
  867. return TRUE_AS_STRING.equals(_cell.getV());
  868. case CELL_TYPE_STRING:
  869. int sstIndex = Integer.parseInt(_cell.getV());
  870. XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.getEntryAt(sstIndex));
  871. String text = rt.getString();
  872. return Boolean.parseBoolean(text);
  873. case CELL_TYPE_NUMERIC:
  874. return Double.parseDouble(_cell.getV()) != 0;
  875. case CELL_TYPE_ERROR:
  876. case CELL_TYPE_BLANK:
  877. return false;
  878. }
  879. throw new RuntimeException("Unexpected cell type (" + cellType + ")");
  880. }
  881. private String convertCellValueToString() {
  882. int cellType = getCellType();
  883. switch (cellType) {
  884. case CELL_TYPE_BLANK:
  885. return "";
  886. case CELL_TYPE_BOOLEAN:
  887. return TRUE_AS_STRING.equals(_cell.getV()) ? "TRUE" : "FALSE";
  888. case CELL_TYPE_STRING:
  889. int sstIndex = Integer.parseInt(_cell.getV());
  890. XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.getEntryAt(sstIndex));
  891. return rt.getString();
  892. case CELL_TYPE_NUMERIC:
  893. case CELL_TYPE_ERROR:
  894. return _cell.getV();
  895. case CELL_TYPE_FORMULA:
  896. // should really evaluate, but HSSFCell can't call HSSFFormulaEvaluator
  897. // just use cached formula result instead
  898. break;
  899. default:
  900. throw new IllegalStateException("Unexpected cell type (" + cellType + ")");
  901. }
  902. cellType = getBaseCellType(false);
  903. String textValue = _cell.getV();
  904. switch (cellType) {
  905. case CELL_TYPE_BOOLEAN:
  906. if (TRUE_AS_STRING.equals(textValue)) {
  907. return "TRUE";
  908. }
  909. if (FALSE_AS_STRING.equals(textValue)) {
  910. return "FALSE";
  911. }
  912. throw new IllegalStateException("Unexpected boolean cached formula value '"
  913. + textValue + "'.");
  914. case CELL_TYPE_STRING:
  915. case CELL_TYPE_NUMERIC:
  916. case CELL_TYPE_ERROR:
  917. return textValue;
  918. }
  919. throw new IllegalStateException("Unexpected formula result type (" + cellType + ")");
  920. }
  921. public CellRangeAddress getArrayFormulaRange() {
  922. XSSFCell cell = getSheet().getFirstCellInArrayFormula(this);
  923. if (cell == null) {
  924. throw new IllegalStateException("Cell " + _cell.getR()
  925. + " is not part of an array formula.");
  926. }
  927. String formulaRef = cell._cell.getF().getRef();
  928. return CellRangeAddress.valueOf(formulaRef);
  929. }
  930. public boolean isPartOfArrayFormulaGroup() {
  931. return getSheet().isCellInArrayFormulaContext(this);
  932. }
  933. /**
  934. * The purpose of this method is to validate the cell state prior to modification
  935. *
  936. * @see #notifyArrayFormulaChanging()
  937. */
  938. void notifyArrayFormulaChanging(String msg){
  939. if(isPartOfArrayFormulaGroup()){
  940. CellRangeAddress cra = getArrayFormulaRange();
  941. if(cra.getNumberOfCells() > 1) {
  942. throw new IllegalStateException(msg);
  943. }
  944. //un-register the single-cell array formula from the parent XSSFSheet
  945. getRow().getSheet().removeArrayFormula(this);
  946. }
  947. }
  948. /**
  949. * Called when this cell is modified.
  950. * <p>
  951. * The purpose of this method is to validate the cell state prior to modification.
  952. * </p>
  953. *
  954. * @see #setCellType(int)
  955. * @see #setCellFormula(String)
  956. * @see XSSFRow#removeCell(org.apache.poi.ss.usermodel.Cell)
  957. * @see org.apache.poi.xssf.usermodel.XSSFSheet#removeRow(org.apache.poi.ss.usermodel.Row)
  958. * @see org.apache.poi.xssf.usermodel.XSSFSheet#shiftRows(int, int, int)
  959. * @see org.apache.poi.xssf.usermodel.XSSFSheet#addMergedRegion(org.apache.poi.ss.util.CellRangeAddress)
  960. * @throws IllegalStateException if modification is not allowed
  961. */
  962. void notifyArrayFormulaChanging(){
  963. CellReference ref = new CellReference(this);
  964. String msg = "Cell "+ref.formatAsString()+" is part of a multi-cell array formula. " +
  965. "You cannot change part of an array.";
  966. notifyArrayFormulaChanging(msg);
  967. }
  968. }