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

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