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

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