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

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