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

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