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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  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.SpreadsheetVersion;
  21. import org.apache.poi.ss.formula.FormulaParser;
  22. import org.apache.poi.ss.formula.FormulaRenderer;
  23. import org.apache.poi.ss.formula.FormulaType;
  24. import org.apache.poi.ss.formula.SharedFormula;
  25. import org.apache.poi.ss.formula.eval.ErrorEval;
  26. import org.apache.poi.ss.formula.ptg.Ptg;
  27. import org.apache.poi.ss.usermodel.Cell;
  28. import org.apache.poi.ss.usermodel.CellCopyPolicy;
  29. import org.apache.poi.ss.usermodel.CellStyle;
  30. import org.apache.poi.ss.usermodel.CellType;
  31. import org.apache.poi.ss.usermodel.Comment;
  32. import org.apache.poi.ss.usermodel.DataFormatter;
  33. import org.apache.poi.ss.usermodel.DateUtil;
  34. import org.apache.poi.ss.usermodel.FormulaError;
  35. import org.apache.poi.ss.usermodel.Hyperlink;
  36. import org.apache.poi.ss.usermodel.RichTextString;
  37. import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
  38. import org.apache.poi.ss.util.CellAddress;
  39. import org.apache.poi.ss.util.CellRangeAddress;
  40. import org.apache.poi.ss.util.CellReference;
  41. import org.apache.poi.util.Beta;
  42. import org.apache.poi.util.Internal;
  43. import org.apache.poi.util.LocaleUtil;
  44. import org.apache.poi.util.Removal;
  45. import org.apache.poi.xssf.model.SharedStringsTable;
  46. import org.apache.poi.xssf.model.StylesTable;
  47. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;
  48. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellFormula;
  49. import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellFormulaType;
  50. import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType;
  51. /**
  52. * High level representation of a cell in a row of a spreadsheet.
  53. * <p>
  54. * Cells can be numeric, formula-based or string-based (text). The cell type
  55. * specifies this. String cells cannot contain numbers and numeric cells cannot
  56. * contain strings (at least according to our model). Client apps should do the
  57. * conversions themselves. Formula cells have the formula string, as well as
  58. * the formula result, which can be numeric or string.
  59. * </p>
  60. * <p>
  61. * Cells should have their number (0 based) before being added to a row. Only
  62. * cells that have values should be added.
  63. * </p>
  64. */
  65. public final class XSSFCell implements Cell {
  66. private static final String FALSE_AS_STRING = "0";
  67. private static final String TRUE_AS_STRING = "1";
  68. private static final String FALSE = "FALSE";
  69. private static final String TRUE = "TRUE";
  70. /**
  71. * the xml bean containing information about the cell's location, value,
  72. * data type, formatting, and formula
  73. */
  74. private CTCell _cell;
  75. /**
  76. * the XSSFRow this cell belongs to
  77. */
  78. private final XSSFRow _row;
  79. /**
  80. * 0-based column index
  81. */
  82. private int _cellNum;
  83. /**
  84. * Table of strings shared across this workbook.
  85. * If two cells contain the same string, then the cell value is the same index into SharedStringsTable
  86. */
  87. private SharedStringsTable _sharedStringSource;
  88. /**
  89. * Table of cell styles shared across all cells in a workbook.
  90. */
  91. private StylesTable _stylesSource;
  92. /**
  93. * Construct a XSSFCell.
  94. *
  95. * @param row the parent row.
  96. * @param cell the xml bean containing information about the cell.
  97. */
  98. protected XSSFCell(XSSFRow row, CTCell cell) {
  99. _cell = cell;
  100. _row = row;
  101. if (cell.getR() != null) {
  102. _cellNum = new CellReference(cell.getR()).getCol();
  103. } else {
  104. int prevNum = row.getLastCellNum();
  105. if(prevNum != -1){
  106. _cellNum = row.getCell(prevNum-1, MissingCellPolicy.RETURN_NULL_AND_BLANK).getColumnIndex() + 1;
  107. }
  108. }
  109. _sharedStringSource = row.getSheet().getWorkbook().getSharedStringSource();
  110. _stylesSource = row.getSheet().getWorkbook().getStylesSource();
  111. }
  112. /**
  113. * Copy cell value, formula and style, from srcCell per cell copy policy
  114. * If srcCell is null, clears the cell value and cell style per cell copy policy
  115. *
  116. * This does not shift references in formulas. Use {@link org.apache.poi.xssf.usermodel.helpers.XSSFRowShifter} to shift references in formulas.
  117. *
  118. * @param srcCell The cell to take value, formula and style from
  119. * @param policy The policy for copying the information, see {@link CellCopyPolicy}
  120. * @throws IllegalArgumentException if copy cell style and srcCell is from a different workbook
  121. */
  122. @Beta
  123. @Internal
  124. public void copyCellFrom(Cell srcCell, CellCopyPolicy policy) {
  125. // Copy cell value (cell type is updated implicitly)
  126. if (policy.isCopyCellValue()) {
  127. if (srcCell != null) {
  128. CellType copyCellType = srcCell.getCellType();
  129. if (copyCellType == CellType.FORMULA && !policy.isCopyCellFormula()) {
  130. // Copy formula result as value
  131. // FIXME: Cached value may be stale
  132. copyCellType = srcCell.getCachedFormulaResultType();
  133. }
  134. switch (copyCellType) {
  135. case NUMERIC:
  136. // DataFormat is not copied unless policy.isCopyCellStyle is true
  137. if (DateUtil.isCellDateFormatted(srcCell)) {
  138. setCellValue(srcCell.getDateCellValue());
  139. }
  140. else {
  141. setCellValue(srcCell.getNumericCellValue());
  142. }
  143. break;
  144. case STRING:
  145. setCellValue(srcCell.getStringCellValue());
  146. break;
  147. case FORMULA:
  148. setCellFormula(srcCell.getCellFormula());
  149. break;
  150. case BLANK:
  151. setBlank();
  152. break;
  153. case BOOLEAN:
  154. setCellValue(srcCell.getBooleanCellValue());
  155. break;
  156. case ERROR:
  157. setCellErrorValue(srcCell.getErrorCellValue());
  158. break;
  159. default:
  160. throw new IllegalArgumentException("Invalid cell type " + srcCell.getCellType());
  161. }
  162. } else { //srcCell is null
  163. setBlank();
  164. }
  165. }
  166. // Copy CellStyle
  167. if (policy.isCopyCellStyle()) {
  168. setCellStyle(srcCell == null ? null : srcCell.getCellStyle());
  169. }
  170. final Hyperlink srcHyperlink = (srcCell == null) ? null : srcCell.getHyperlink();
  171. if (policy.isMergeHyperlink()) {
  172. // if srcCell doesn't have a hyperlink and destCell has a hyperlink, don't clear destCell's hyperlink
  173. if (srcHyperlink != null) {
  174. setHyperlink(new XSSFHyperlink(srcHyperlink));
  175. }
  176. } else if (policy.isCopyHyperlink()) {
  177. // overwrite the hyperlink at dest cell with srcCell's hyperlink
  178. // if srcCell doesn't have a hyperlink, clear the hyperlink (if one exists) at destCell
  179. setHyperlink(srcHyperlink == null ? null : new XSSFHyperlink(srcHyperlink));
  180. }
  181. }
  182. /**
  183. * @return table of strings shared across this workbook
  184. */
  185. protected SharedStringsTable getSharedStringSource() {
  186. return _sharedStringSource;
  187. }
  188. /**
  189. * @return table of cell styles shared across this workbook
  190. */
  191. protected StylesTable getStylesSource() {
  192. return _stylesSource;
  193. }
  194. /**
  195. * Returns the sheet this cell belongs to
  196. *
  197. * @return the sheet this cell belongs to
  198. */
  199. @Override
  200. public XSSFSheet getSheet() {
  201. return getRow().getSheet();
  202. }
  203. /**
  204. * Returns the row this cell belongs to
  205. *
  206. * @return the row this cell belongs to
  207. */
  208. @Override
  209. public XSSFRow getRow() {
  210. return _row;
  211. }
  212. /**
  213. * Get the value of the cell as a boolean.
  214. * <p>
  215. * For strings, numbers, and errors, we throw an exception. For blank cells we return a false.
  216. * </p>
  217. * @return the value of the cell as a boolean
  218. * @throws IllegalStateException if the cell type returned by {@link #getCellType()}
  219. * is not {@link CellType#BOOLEAN}, {@link CellType#BLANK} or {@link CellType#FORMULA}
  220. */
  221. @Override
  222. public boolean getBooleanCellValue() {
  223. CellType cellType = getCellType();
  224. switch(cellType) {
  225. case BLANK:
  226. return false;
  227. case BOOLEAN:
  228. return _cell.isSetV() && TRUE_AS_STRING.equals(_cell.getV());
  229. case FORMULA:
  230. //YK: should throw an exception if requesting boolean value from a non-boolean formula
  231. return _cell.isSetV() && TRUE_AS_STRING.equals(_cell.getV());
  232. default:
  233. throw typeMismatch(CellType.BOOLEAN, cellType, false);
  234. }
  235. }
  236. /**
  237. * Set a boolean value for the cell
  238. *
  239. * @param value the boolean value to set this cell to. For formulas we'll set the
  240. * precalculated value, for booleans we'll set its value. For other types we
  241. * will change the cell to a boolean cell and set its value.
  242. */
  243. @Override
  244. public void setCellValue(boolean value) {
  245. _cell.setT(STCellType.B);
  246. _cell.setV(value ? TRUE_AS_STRING : FALSE_AS_STRING);
  247. }
  248. /**
  249. * Get the value of the cell as a number.
  250. * <p>
  251. * For strings we throw an exception. For blank cells we return a 0.
  252. * For formulas or error cells we return the precalculated value;
  253. * </p>
  254. * @return the value of the cell as a number
  255. * @throws IllegalStateException if the cell type returned by {@link #getCellType()} is {@link CellType#STRING}
  256. * @exception NumberFormatException if the cell value isn't a parsable <code>double</code>.
  257. * @see DataFormatter for turning this number into a string similar to that which Excel would render this number as.
  258. */
  259. @Override
  260. public double getNumericCellValue() {
  261. CellType cellType = getCellType();
  262. switch(cellType) {
  263. case BLANK:
  264. return 0.0;
  265. case FORMULA:
  266. // fall-through
  267. case NUMERIC:
  268. if(_cell.isSetV()) {
  269. String v = _cell.getV();
  270. if (v.isEmpty()) {
  271. return 0.0;
  272. }
  273. try {
  274. return Double.parseDouble(v);
  275. } catch(NumberFormatException e) {
  276. throw typeMismatch(CellType.NUMERIC, CellType.STRING, false);
  277. }
  278. } else {
  279. return 0.0;
  280. }
  281. default:
  282. throw typeMismatch(CellType.NUMERIC, cellType, false);
  283. }
  284. }
  285. /**
  286. * Set a numeric value for the cell
  287. *
  288. * @param value the numeric value to set this cell to. For formulas we'll set the
  289. * precalculated value, for numerics we'll set its value. For other types we
  290. * will change the cell to a numeric cell and set its value.
  291. */
  292. @Override
  293. public void setCellValue(double value) {
  294. if(Double.isInfinite(value)) {
  295. // Excel does not support positive/negative infinities,
  296. // rather, it gives a #DIV/0! error in these cases.
  297. _cell.setT(STCellType.E);
  298. _cell.setV(FormulaError.DIV0.getString());
  299. } else if (Double.isNaN(value)){
  300. // Excel does not support Not-a-Number (NaN),
  301. // instead it immediately generates an #NUM! error.
  302. _cell.setT(STCellType.E);
  303. _cell.setV(FormulaError.NUM.getString());
  304. } else {
  305. _cell.setT(STCellType.N);
  306. _cell.setV(String.valueOf(value));
  307. }
  308. }
  309. /**
  310. * Get the value of the cell as a string
  311. * <p>
  312. * For numeric cells we throw an exception. For blank cells we return an empty string.
  313. * For formulaCells that are not string Formulas, we throw an exception
  314. * </p>
  315. * @return the value of the cell as a string
  316. */
  317. @Override
  318. public String getStringCellValue() {
  319. return getRichStringCellValue().getString();
  320. }
  321. /**
  322. * Get the value of the cell as a XSSFRichTextString
  323. * <p>
  324. * For numeric cells we throw an exception. For blank cells we return an empty string.
  325. * For formula cells we return the pre-calculated value if a string, otherwise an exception
  326. * </p>
  327. * @return the value of the cell as a XSSFRichTextString
  328. */
  329. @Override
  330. public XSSFRichTextString getRichStringCellValue() {
  331. CellType cellType = getCellType();
  332. XSSFRichTextString rt;
  333. switch (cellType) {
  334. case BLANK:
  335. rt = new XSSFRichTextString("");
  336. break;
  337. case STRING:
  338. if (_cell.getT() == STCellType.INLINE_STR) {
  339. if(_cell.isSetIs()) {
  340. //string is expressed directly in the cell definition instead of implementing the shared string table.
  341. rt = new XSSFRichTextString(_cell.getIs());
  342. } else if (_cell.isSetV()) {
  343. //cached result of a formula
  344. rt = new XSSFRichTextString(_cell.getV());
  345. } else {
  346. rt = new XSSFRichTextString("");
  347. }
  348. } else if (_cell.getT() == STCellType.STR) {
  349. //cached formula value
  350. rt = new XSSFRichTextString(_cell.isSetV() ? _cell.getV() : "");
  351. } else {
  352. if (_cell.isSetV()) {
  353. int idx = Integer.parseInt(_cell.getV());
  354. rt = new XSSFRichTextString(_sharedStringSource.getEntryAt(idx));
  355. }
  356. else {
  357. rt = new XSSFRichTextString("");
  358. }
  359. }
  360. break;
  361. case FORMULA:
  362. checkFormulaCachedValueType(CellType.STRING, getBaseCellType(false));
  363. rt = new XSSFRichTextString(_cell.isSetV() ? _cell.getV() : "");
  364. break;
  365. default:
  366. throw typeMismatch(CellType.STRING, cellType, false);
  367. }
  368. rt.setStylesTableReference(_stylesSource);
  369. return rt;
  370. }
  371. private static void checkFormulaCachedValueType(CellType expectedTypeCode, CellType cachedValueType) {
  372. if (cachedValueType != expectedTypeCode) {
  373. throw typeMismatch(expectedTypeCode, cachedValueType, true);
  374. }
  375. }
  376. /**
  377. * Set a string value for the cell.
  378. *
  379. * @param str value to set the cell to. For formulas we'll set the formula
  380. * cached string result, for String cells we'll set its value. For other types we will
  381. * change the cell to a string cell and set its value.
  382. * If value is null then we will change the cell to a Blank cell.
  383. */
  384. @Override
  385. public void setCellValue(String str) {
  386. setCellValue(str == null ? null : new XSSFRichTextString(str));
  387. }
  388. /**
  389. * Set a string value for the cell.
  390. *
  391. * @param str value to set the cell to. For formulas we'll set the 'pre-evaluated result string,
  392. * for String cells we'll set its value. For other types we will
  393. * change the cell to a string cell and set its value.
  394. * If value is null then we will change the cell to a Blank cell.
  395. */
  396. @Override
  397. public void setCellValue(RichTextString str) {
  398. if(str == null || str.getString() == null){
  399. setCellType(CellType.BLANK);
  400. return;
  401. }
  402. if(str.length() > SpreadsheetVersion.EXCEL2007.getMaxTextLength()){
  403. throw new IllegalArgumentException("The maximum length of cell contents (text) is 32,767 characters");
  404. }
  405. CellType cellType = getCellType();
  406. switch (cellType){
  407. case FORMULA:
  408. _cell.setV(str.getString());
  409. _cell.setT(STCellType.STR);
  410. break;
  411. default:
  412. if(_cell.getT() == STCellType.INLINE_STR) {
  413. //set the 'pre-evaluated result
  414. _cell.setV(str.getString());
  415. } else {
  416. _cell.setT(STCellType.S);
  417. XSSFRichTextString rt = (XSSFRichTextString)str;
  418. rt.setStylesTableReference(_stylesSource);
  419. int sRef = _sharedStringSource.addSharedStringItem(rt);
  420. _cell.setV(Integer.toString(sRef));
  421. }
  422. break;
  423. }
  424. }
  425. /**
  426. * Return a formula for the cell, for example, <code>SUM(C4:E4)</code>
  427. *
  428. * @return a formula for the cell
  429. * @throws IllegalStateException if the cell type returned by {@link #getCellType()} is not {@link CellType#FORMULA}
  430. */
  431. @Override
  432. public String getCellFormula() {
  433. // existing behavior - create a new XSSFEvaluationWorkbook for every call
  434. return getCellFormula(null);
  435. }
  436. /**
  437. * package/hierarchy use only - reuse an existing evaluation workbook if available for caching
  438. *
  439. * @param fpb evaluation workbook for reuse, if available, or null to create a new one as needed
  440. * @return a formula for the cell
  441. * @throws IllegalStateException if the cell type returned by {@link #getCellType()} is not {@link CellType#FORMULA}
  442. */
  443. protected String getCellFormula(XSSFEvaluationWorkbook fpb) {
  444. CellType cellType = getCellType();
  445. if(cellType != CellType.FORMULA) {
  446. throw typeMismatch(CellType.FORMULA, cellType, false);
  447. }
  448. CTCellFormula f = _cell.getF();
  449. if (isPartOfArrayFormulaGroup()) {
  450. /* In an excel generated array formula, the formula property might be set, but the string is empty in slave cells */
  451. if (f == null || f.getStringValue().isEmpty()) {
  452. XSSFCell cell = getSheet().getFirstCellInArrayFormula(this);
  453. return cell.getCellFormula(fpb);
  454. }
  455. }
  456. if (f.getT() == STCellFormulaType.SHARED) {
  457. return convertSharedFormula((int)f.getSi(), fpb == null ? XSSFEvaluationWorkbook.create(getSheet().getWorkbook()) : fpb);
  458. }
  459. return f.getStringValue();
  460. }
  461. /**
  462. * Creates a non shared formula from the shared formula counterpart
  463. *
  464. * @param si Shared Group Index
  465. * @return non shared formula created for the given shared formula and this cell
  466. */
  467. private String convertSharedFormula(int si, XSSFEvaluationWorkbook fpb){
  468. XSSFSheet sheet = getSheet();
  469. CTCellFormula f = sheet.getSharedFormula(si);
  470. if(f == null) {
  471. throw new IllegalStateException(
  472. "Master cell of a shared formula with sid="+si+" was not found");
  473. }
  474. String sharedFormula = f.getStringValue();
  475. //Range of cells which the shared formula applies to
  476. String sharedFormulaRange = f.getRef();
  477. CellRangeAddress ref = CellRangeAddress.valueOf(sharedFormulaRange);
  478. int sheetIndex = sheet.getWorkbook().getSheetIndex(sheet);
  479. SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL2007);
  480. Ptg[] ptgs = FormulaParser.parse(sharedFormula, fpb, FormulaType.CELL, sheetIndex, getRowIndex());
  481. Ptg[] fmla = sf.convertSharedFormulas(ptgs,
  482. getRowIndex() - ref.getFirstRow(), getColumnIndex() - ref.getFirstColumn());
  483. return FormulaRenderer.toFormulaString(fpb, fmla);
  484. }
  485. /**
  486. * Sets formula for this cell.
  487. * <p>
  488. * Note, this method only sets the formula string and does not calculate the formula value.
  489. * To set the precalculated value use {@link #setCellValue(double)} or {@link #setCellValue(String)}
  490. * </p>
  491. *
  492. * @param formula the formula to set, e.g. <code>"SUM(C4:E4)"</code>.
  493. * If the argument is <code>null</code> then the current formula is removed.
  494. * @throws org.apache.poi.ss.formula.FormulaParseException if the formula has incorrect syntax or is otherwise invalid
  495. * @throws IllegalStateException if the operation is not allowed, for example,
  496. * when the cell is a part of a multi-cell array formula
  497. */
  498. @Override
  499. public void setCellFormula(String formula) {
  500. if(isPartOfArrayFormulaGroup()){
  501. notifyArrayFormulaChanging();
  502. }
  503. setFormula(formula, FormulaType.CELL);
  504. }
  505. /* package */ void setCellArrayFormula(String formula, CellRangeAddress range) {
  506. setFormula(formula, FormulaType.ARRAY);
  507. CTCellFormula cellFormula = _cell.getF();
  508. cellFormula.setT(STCellFormulaType.ARRAY);
  509. cellFormula.setRef(range.formatAsString());
  510. }
  511. private void setFormula(String formula, FormulaType formulaType) {
  512. XSSFWorkbook wb = _row.getSheet().getWorkbook();
  513. if (formula == null) {
  514. wb.onDeleteFormula(this);
  515. if (_cell.isSetF()) {
  516. _row.getSheet().onDeleteFormula(this);
  517. _cell.unsetF();
  518. }
  519. return;
  520. }
  521. if (wb.getCellFormulaValidation()) {
  522. XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb);
  523. //validate through the FormulaParser
  524. FormulaParser.parse(formula, fpb, formulaType, wb.getSheetIndex(getSheet()), getRowIndex());
  525. }
  526. CTCellFormula f;
  527. if (_cell.isSetF()) {
  528. f = _cell.getF();
  529. f.setStringValue(formula);
  530. if(f.getT() == STCellFormulaType.SHARED){
  531. getRow().getSheet().onReadCell(this);
  532. }
  533. } else {
  534. f = CTCellFormula.Factory.newInstance();
  535. f.setStringValue(formula);
  536. _cell.setF(f);
  537. }
  538. if(_cell.isSetV()) {
  539. _cell.unsetV();
  540. }
  541. }
  542. /**
  543. * Returns column index of this cell
  544. *
  545. * @return zero-based column index of a column in a sheet.
  546. */
  547. @Override
  548. public int getColumnIndex() {
  549. return this._cellNum;
  550. }
  551. /**
  552. * Returns row index of a row in the sheet that contains this cell
  553. *
  554. * @return zero-based row index of a row in the sheet that contains this cell
  555. */
  556. @Override
  557. public int getRowIndex() {
  558. return _row.getRowNum();
  559. }
  560. /**
  561. * Returns an A1 style reference to the location of this cell
  562. *
  563. * @return A1 style reference to the location of this cell
  564. */
  565. public String getReference() {
  566. String ref = _cell.getR();
  567. if(ref == null) {
  568. return getAddress().formatAsString();
  569. }
  570. return ref;
  571. }
  572. /**
  573. * {@inheritDoc}
  574. */
  575. @Override
  576. public CellAddress getAddress() {
  577. return new CellAddress(this);
  578. }
  579. /**
  580. * Return the cell's style.
  581. *
  582. * @return the cell's style.
  583. */
  584. @Override
  585. public XSSFCellStyle getCellStyle() {
  586. XSSFCellStyle style = null;
  587. if(_stylesSource.getNumCellStyles() > 0){
  588. long idx = _cell.isSetS() ? _cell.getS() : 0;
  589. style = _stylesSource.getStyleAt((int)idx);
  590. }
  591. return style;
  592. }
  593. /**
  594. * <p>Set the style for the cell. The style should be an XSSFCellStyle created/retreived from
  595. * the XSSFWorkbook.</p>
  596. *
  597. * <p>To change the style of a cell without affecting other cells that use the same style,
  598. * use {@link org.apache.poi.ss.util.CellUtil#setCellStyleProperties(Cell, java.util.Map)}</p>
  599. *
  600. * @param style reference contained in the workbook.
  601. * If the value is null then the style information is removed causing the cell to used the default workbook style.
  602. * @throws IllegalArgumentException if style belongs to a different styles source (most likely because style is from a different Workbook)
  603. */
  604. @Override
  605. public void setCellStyle(CellStyle style) {
  606. if(style == null) {
  607. if(_cell.isSetS()) {
  608. _cell.unsetS();
  609. }
  610. } else {
  611. XSSFCellStyle xStyle = (XSSFCellStyle)style;
  612. xStyle.verifyBelongsToStylesSource(_stylesSource);
  613. long idx = _stylesSource.putStyle(xStyle);
  614. _cell.setS(idx);
  615. }
  616. }
  617. /**
  618. * POI currently supports these formula types:
  619. * <ul>
  620. * <li> {@link STCellFormulaType#NORMAL}
  621. * <li> {@link STCellFormulaType#SHARED}
  622. * <li> {@link STCellFormulaType#ARRAY}
  623. * </ul>
  624. * POI does not support {@link STCellFormulaType#DATA_TABLE} formulas.
  625. * @return true if the cell is of a formula type POI can handle
  626. */
  627. private boolean isFormulaCell() {
  628. if ( (_cell.isSetF() && _cell.getF().getT() != STCellFormulaType.DATA_TABLE ) || getSheet().isCellInArrayFormulaContext(this)) {
  629. return true;
  630. }
  631. return false;
  632. }
  633. /**
  634. * Return the cell type. Tables in an array formula return
  635. * {@link CellType#FORMULA} for all cells, even though the formula is only defined
  636. * in the OOXML file for the top left cell of the array.
  637. * <p>
  638. * NOTE: POI does not support data table formulas.
  639. * Cells in a data table appear to POI as plain cells typed from their cached value.
  640. *
  641. * @return the cell type
  642. */
  643. @Override
  644. public CellType getCellType() {
  645. if (isFormulaCell()) {
  646. return CellType.FORMULA;
  647. }
  648. return getBaseCellType(true);
  649. }
  650. /**
  651. * Return the cell type. Tables in an array formula return
  652. * {@link CellType#FORMULA} for all cells, even though the formula is only defined
  653. * in the OOXML file for the top left cell of the array.
  654. * <p>
  655. * NOTE: POI does not support data table formulas.
  656. * Cells in a data table appear to POI as plain cells typed from their cached value.
  657. *
  658. * @return the cell type
  659. * @since POI 3.15 beta 3
  660. * @deprecated use <code>getCellType</code> instead
  661. */
  662. @Deprecated
  663. @Removal(version = "4.2")
  664. @Override
  665. public CellType getCellTypeEnum() {
  666. return getCellType();
  667. }
  668. /**
  669. * Only valid for formula cells
  670. * @return one of ({@link CellType#NUMERIC}, {@link CellType#STRING},
  671. * {@link CellType#BOOLEAN}, {@link CellType#ERROR}) depending
  672. * on the cached value of the formula
  673. */
  674. @Override
  675. public CellType getCachedFormulaResultType() {
  676. if (! isFormulaCell()) {
  677. throw new IllegalStateException("Only formula cells have cached results");
  678. }
  679. return getBaseCellType(false);
  680. }
  681. /**
  682. * Only valid for formula cells
  683. * @return one of ({@link CellType#NUMERIC}, {@link CellType#STRING},
  684. * {@link CellType#BOOLEAN}, {@link CellType#ERROR}) depending
  685. * on the cached value of the formula
  686. * @since POI 3.15 beta 3
  687. * @deprecated use <code>getCachedFormulaResultType</code> instead
  688. * Will be deleted when we make the CellType enum transition. See bug 59791.
  689. */
  690. @Deprecated
  691. @Removal(version = "4.2")
  692. @Override
  693. public CellType getCachedFormulaResultTypeEnum() {
  694. return getCachedFormulaResultType();
  695. }
  696. /**
  697. * Detect cell type based on the "t" attribute of the CTCell bean
  698. */
  699. private CellType getBaseCellType(boolean blankCells) {
  700. switch (_cell.getT().intValue()) {
  701. case STCellType.INT_B:
  702. return CellType.BOOLEAN;
  703. case STCellType.INT_N:
  704. if (!_cell.isSetV() && blankCells) {
  705. // ooxml does have a separate cell type of 'blank'. A blank cell gets encoded as
  706. // (either not present or) a numeric cell with no value set.
  707. // The formula evaluator (and perhaps other clients of this interface) needs to
  708. // distinguish blank values which sometimes get translated into zero and sometimes
  709. // empty string, depending on context
  710. return CellType.BLANK;
  711. }
  712. return CellType.NUMERIC;
  713. case STCellType.INT_E:
  714. return CellType.ERROR;
  715. case STCellType.INT_S: // String is in shared strings
  716. case STCellType.INT_INLINE_STR: // String is inline in cell
  717. case STCellType.INT_STR:
  718. return CellType.STRING;
  719. default:
  720. throw new IllegalStateException("Illegal cell type: " + this._cell.getT());
  721. }
  722. }
  723. /**
  724. * Get the value of the cell as a date.
  725. * <p>
  726. * For strings we throw an exception. For blank cells we return a null.
  727. * </p>
  728. * @return the value of the cell as a date
  729. * @throws IllegalStateException if the cell type returned by {@link #getCellType()} is {@link CellType#STRING}
  730. * @exception NumberFormatException if the cell value isn't a parsable <code>double</code>.
  731. * @see DataFormatter for formatting this date into a string similar to how excel does.
  732. */
  733. @Override
  734. public Date getDateCellValue() {
  735. if (getCellType() == CellType.BLANK) {
  736. return null;
  737. }
  738. double value = getNumericCellValue();
  739. boolean date1904 = getSheet().getWorkbook().isDate1904();
  740. return DateUtil.getJavaDate(value, date1904);
  741. }
  742. /**
  743. * Set a date value for the cell. Excel treats dates as numeric so you will need to format the cell as
  744. * a date.
  745. *
  746. * @param value the date value to set this cell to. For formulas we'll set the
  747. * precalculated value, for numerics we'll set its value. For other types we
  748. * will change the cell to a numeric cell and set its value.
  749. */
  750. @Override
  751. public void setCellValue(Date value) {
  752. if(value == null) {
  753. setCellType(CellType.BLANK);
  754. return;
  755. }
  756. boolean date1904 = getSheet().getWorkbook().isDate1904();
  757. setCellValue(DateUtil.getExcelDate(value, date1904));
  758. }
  759. /**
  760. * Set a date value for the cell. Excel treats dates as numeric so you will need to format the cell as
  761. * a date.
  762. * <p>
  763. * This will set the cell value based on the Calendar's timezone. As Excel
  764. * does not support timezones this means that both 20:00+03:00 and
  765. * 20:00-03:00 will be reported as the same value (20:00) even that there
  766. * are 6 hours difference between the two times. This difference can be
  767. * preserved by using <code>setCellValue(value.getTime())</code> which will
  768. * automatically shift the times to the default timezone.
  769. * </p>
  770. *
  771. * @param value the date value to set this cell to. For formulas we'll set the
  772. * precalculated value, for numerics we'll set its value. For othertypes we
  773. * will change the cell to a numeric cell and set its value.
  774. */
  775. @Override
  776. public void setCellValue(Calendar value) {
  777. if(value == null) {
  778. setCellType(CellType.BLANK);
  779. return;
  780. }
  781. boolean date1904 = getSheet().getWorkbook().isDate1904();
  782. setCellValue( DateUtil.getExcelDate(value, date1904 ));
  783. }
  784. /**
  785. * Returns the error message, such as #VALUE!
  786. *
  787. * @return the error message such as #VALUE!
  788. * @throws IllegalStateException if the cell type returned by {@link #getCellType()} isn't {@link CellType#ERROR}
  789. * @see FormulaError
  790. */
  791. public String getErrorCellString() throws IllegalStateException {
  792. CellType cellType = getBaseCellType(true);
  793. if(cellType != CellType.ERROR) {
  794. throw typeMismatch(CellType.ERROR, cellType, false);
  795. }
  796. return _cell.getV();
  797. }
  798. /**
  799. * Get the value of the cell as an error code.
  800. * <p>
  801. * For strings, numbers, and booleans, we throw an exception.
  802. * For blank cells we return a 0.
  803. * </p>
  804. *
  805. * @return the value of the cell as an error code
  806. * @throws IllegalStateException if the cell type returned by {@link #getCellType()} isn't {@link CellType #ERROR}
  807. * @see FormulaError
  808. */
  809. @Override
  810. public byte getErrorCellValue() throws IllegalStateException {
  811. String code = getErrorCellString();
  812. if (code == null) {
  813. return 0;
  814. }
  815. try {
  816. return FormulaError.forString(code).getCode();
  817. } catch (final IllegalArgumentException e) {
  818. throw new IllegalStateException("Unexpected error code", e);
  819. }
  820. }
  821. /**
  822. * Set a error value for the cell
  823. *
  824. * @param errorCode the error value to set this cell to. For formulas we'll set the
  825. * precalculated value , for errors we'll set
  826. * its value. For other types we will change the cell to an error
  827. * cell and set its value.
  828. * @see FormulaError
  829. */
  830. @Override
  831. public void setCellErrorValue(byte errorCode) {
  832. FormulaError error = FormulaError.forInt(errorCode);
  833. setCellErrorValue(error);
  834. }
  835. /**
  836. * Set a error value for the cell
  837. *
  838. * @param error the error value to set this cell to. For formulas we'll set the
  839. * precalculated value , for errors we'll set
  840. * its value. For other types we will change the cell to an error
  841. * cell and set its value.
  842. */
  843. public void setCellErrorValue(FormulaError error) {
  844. _cell.setT(STCellType.E);
  845. _cell.setV(error.getString());
  846. }
  847. /**
  848. * {@inheritDoc}
  849. */
  850. @Override
  851. public void setAsActiveCell() {
  852. getSheet().setActiveCell(getAddress());
  853. }
  854. /**
  855. * Blanks this cell. Blank cells have no formula or value but may have styling.
  856. * This method erases all the data previously associated with this cell.
  857. */
  858. private void setBlank(){
  859. CTCell blank = CTCell.Factory.newInstance();
  860. blank.setR(_cell.getR());
  861. if(_cell.isSetS()) {
  862. blank.setS(_cell.getS());
  863. }
  864. _cell.set(blank);
  865. }
  866. /**
  867. * Sets column index of this cell
  868. *
  869. * @param num column index of this cell
  870. */
  871. protected void setCellNum(int num) {
  872. checkBounds(num);
  873. _cellNum = num;
  874. String ref = new CellReference(getRowIndex(), getColumnIndex()).formatAsString();
  875. _cell.setR(ref);
  876. }
  877. /**
  878. * Set the cells type (numeric, formula or string)
  879. *
  880. * @throws IllegalArgumentException if the specified cell type is invalid
  881. */
  882. @Override
  883. public void setCellType(CellType cellType) {
  884. CellType prevType = getCellType();
  885. if(isPartOfArrayFormulaGroup()){
  886. notifyArrayFormulaChanging();
  887. }
  888. if(prevType == CellType.FORMULA && cellType != CellType.FORMULA) {
  889. if (_cell.isSetF()) {
  890. _row.getSheet().onDeleteFormula(this);
  891. }
  892. getSheet().getWorkbook().onDeleteFormula(this);
  893. }
  894. switch (cellType) {
  895. case NUMERIC:
  896. _cell.setT(STCellType.N);
  897. break;
  898. case STRING:
  899. if(prevType != CellType.STRING){
  900. String str = convertCellValueToString();
  901. XSSFRichTextString rt = new XSSFRichTextString(str);
  902. rt.setStylesTableReference(_stylesSource);
  903. int sRef = _sharedStringSource.addSharedStringItem(rt);
  904. _cell.setV(Integer.toString(sRef));
  905. }
  906. _cell.setT(STCellType.S);
  907. break;
  908. case FORMULA:
  909. if(!_cell.isSetF()){
  910. CTCellFormula f = CTCellFormula.Factory.newInstance();
  911. f.setStringValue("0");
  912. _cell.setF(f);
  913. if(_cell.isSetT()) {
  914. _cell.unsetT();
  915. }
  916. }
  917. break;
  918. case BLANK:
  919. setBlank();
  920. break;
  921. case BOOLEAN:
  922. String newVal = convertCellValueToBoolean() ? TRUE_AS_STRING : FALSE_AS_STRING;
  923. _cell.setT(STCellType.B);
  924. _cell.setV(newVal);
  925. break;
  926. case ERROR:
  927. _cell.setT(STCellType.E);
  928. break;
  929. default:
  930. throw new IllegalArgumentException("Illegal cell type: " + cellType);
  931. }
  932. if (cellType != CellType.FORMULA && _cell.isSetF()) {
  933. _cell.unsetF();
  934. }
  935. }
  936. /**
  937. * Returns a string representation of the cell
  938. * <p>
  939. * Formula cells return the formula string, rather than the formula result.
  940. * Dates are displayed in dd-MMM-yyyy format
  941. * Errors are displayed as #ERR&lt;errIdx&gt;
  942. * </p>
  943. */
  944. @Override
  945. public String toString() {
  946. switch (getCellType()) {
  947. case NUMERIC:
  948. if (DateUtil.isCellDateFormatted(this)) {
  949. DateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", LocaleUtil.getUserLocale());
  950. sdf.setTimeZone(LocaleUtil.getUserTimeZone());
  951. return sdf.format(getDateCellValue());
  952. }
  953. return Double.toString(getNumericCellValue());
  954. case STRING:
  955. return getRichStringCellValue().toString();
  956. case FORMULA:
  957. return getCellFormula();
  958. case BLANK:
  959. return "";
  960. case BOOLEAN:
  961. return getBooleanCellValue() ? TRUE : FALSE;
  962. case ERROR:
  963. return ErrorEval.getText(getErrorCellValue());
  964. default:
  965. return "Unknown Cell Type: " + getCellType();
  966. }
  967. }
  968. /**
  969. * Returns the raw, underlying ooxml value for the cell
  970. * <p>
  971. * If the cell contains a string, then this value is an index into
  972. * the shared string table, pointing to the actual string value. Otherwise,
  973. * the value of the cell is expressed directly in this element. Cells containing formulas express
  974. * the last calculated result of the formula in this element.
  975. * </p>
  976. *
  977. * @return the raw cell value as contained in the underlying CTCell bean,
  978. * <code>null</code> for blank cells.
  979. */
  980. public String getRawValue() {
  981. return _cell.getV();
  982. }
  983. /**
  984. * Used to help format error messages
  985. */
  986. private static RuntimeException typeMismatch(CellType expectedType, CellType actualType, boolean isFormulaCell) {
  987. String msg = "Cannot get a " + expectedType + " value from a " + actualType+ " " + (isFormulaCell ? "formula " : "") + "cell";
  988. return new IllegalStateException(msg);
  989. }
  990. /**
  991. * @throws RuntimeException if the bounds are exceeded.
  992. */
  993. private static void checkBounds(int cellIndex) {
  994. SpreadsheetVersion v = SpreadsheetVersion.EXCEL2007;
  995. int maxcol = SpreadsheetVersion.EXCEL2007.getLastColumnIndex();
  996. if (cellIndex < 0 || cellIndex > maxcol) {
  997. throw new IllegalArgumentException("Invalid column index (" + cellIndex
  998. + "). Allowable column range for " + v.name() + " is (0.."
  999. + maxcol + ") or ('A'..'" + v.getLastColumnName() + "')");
  1000. }
  1001. }
  1002. /**
  1003. * Returns cell comment associated with this cell
  1004. *
  1005. * @return the cell comment associated with this cell or <code>null</code>
  1006. */
  1007. @Override
  1008. public XSSFComment getCellComment() {
  1009. return getSheet().getCellComment(new CellAddress(this));
  1010. }
  1011. /**
  1012. * Assign a comment to this cell. If the supplied comment is null,
  1013. * the comment for this cell will be removed.
  1014. *
  1015. * @param comment the XSSFComment associated with this cell
  1016. */
  1017. @Override
  1018. public void setCellComment(Comment comment) {
  1019. if(comment == null) {
  1020. removeCellComment();
  1021. return;
  1022. }
  1023. comment.setAddress(getRowIndex(), getColumnIndex());
  1024. }
  1025. /**
  1026. * Removes the comment for this cell, if there is one.
  1027. */
  1028. @Override
  1029. public void removeCellComment() {
  1030. XSSFComment comment = getCellComment();
  1031. if(comment != null){
  1032. CellAddress ref = new CellAddress(getReference());
  1033. XSSFSheet sh = getSheet();
  1034. sh.getCommentsTable(false).removeComment(ref);
  1035. sh.getVMLDrawing(false).removeCommentShape(getRowIndex(), getColumnIndex());
  1036. }
  1037. }
  1038. /**
  1039. * Returns hyperlink associated with this cell
  1040. *
  1041. * @return hyperlink associated with this cell or <code>null</code> if not found
  1042. */
  1043. @Override
  1044. public XSSFHyperlink getHyperlink() {
  1045. return getSheet().getHyperlink(_row.getRowNum(), _cellNum);
  1046. }
  1047. /**
  1048. * Assign a hyperlink to this cell. If the supplied hyperlink is null, the
  1049. * hyperlink for this cell will be removed.
  1050. *
  1051. * @param hyperlink the hyperlink to associate with this cell
  1052. */
  1053. @Override
  1054. public void setHyperlink(Hyperlink hyperlink) {
  1055. if (hyperlink == null) {
  1056. removeHyperlink();
  1057. return;
  1058. }
  1059. XSSFHyperlink link = (XSSFHyperlink)hyperlink;
  1060. // Assign to us
  1061. link.setCellReference( new CellReference(_row.getRowNum(), _cellNum).formatAsString() );
  1062. // Add to the lists
  1063. getSheet().addHyperlink(link);
  1064. }
  1065. /**
  1066. * Removes the hyperlink for this cell, if there is one.
  1067. */
  1068. @Override
  1069. public void removeHyperlink() {
  1070. getSheet().removeHyperlink(_row.getRowNum(), _cellNum);
  1071. }
  1072. /**
  1073. * Returns the xml bean containing information about the cell's location (reference), value,
  1074. * data type, formatting, and formula
  1075. *
  1076. * @return the xml bean containing information about this cell
  1077. */
  1078. @Internal
  1079. public CTCell getCTCell(){
  1080. return _cell;
  1081. }
  1082. /**
  1083. * Set a new internal xml bean. This is only for internal use, do not call this from outside!
  1084. *
  1085. * This is necessary in some rare cases to work around XMLBeans specialties.
  1086. */
  1087. @Internal
  1088. public void setCTCell(CTCell cell) {
  1089. _cell = cell;
  1090. }
  1091. /**
  1092. * Chooses a new boolean value for the cell when its type is changing.<p>
  1093. *
  1094. * Usually the caller is calling setCellType() with the intention of calling
  1095. * setCellValue(boolean) straight afterwards. This method only exists to give
  1096. * the cell a somewhat reasonable value until the setCellValue() call (if at all).
  1097. * TODO - perhaps a method like setCellTypeAndValue(CellType, Object) should be introduced to avoid this
  1098. */
  1099. private boolean convertCellValueToBoolean() {
  1100. CellType cellType = getCellType();
  1101. if (cellType == CellType.FORMULA) {
  1102. cellType = getBaseCellType(false);
  1103. }
  1104. switch (cellType) {
  1105. case BOOLEAN:
  1106. return TRUE_AS_STRING.equals(_cell.getV());
  1107. case STRING:
  1108. int sstIndex = Integer.parseInt(_cell.getV());
  1109. XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.getEntryAt(sstIndex));
  1110. String text = rt.getString();
  1111. return Boolean.parseBoolean(text);
  1112. case NUMERIC:
  1113. return Double.parseDouble(_cell.getV()) != 0;
  1114. case ERROR:
  1115. // fall-through
  1116. case BLANK:
  1117. return false;
  1118. default:
  1119. throw new RuntimeException("Unexpected cell type (" + cellType + ")");
  1120. }
  1121. }
  1122. private String convertCellValueToString() {
  1123. CellType cellType = getCellType();
  1124. switch (cellType) {
  1125. case BLANK:
  1126. return "";
  1127. case BOOLEAN:
  1128. return TRUE_AS_STRING.equals(_cell.getV()) ? TRUE : FALSE;
  1129. case STRING:
  1130. int sstIndex = Integer.parseInt(_cell.getV());
  1131. XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.getEntryAt(sstIndex));
  1132. return rt.getString();
  1133. case NUMERIC:
  1134. case ERROR:
  1135. return _cell.getV();
  1136. case FORMULA:
  1137. // should really evaluate, but HSSFCell can't call HSSFFormulaEvaluator
  1138. // just use cached formula result instead
  1139. break;
  1140. default:
  1141. throw new IllegalStateException("Unexpected cell type (" + cellType + ")");
  1142. }
  1143. cellType = getBaseCellType(false);
  1144. String textValue = _cell.getV();
  1145. switch (cellType) {
  1146. case BOOLEAN:
  1147. if (TRUE_AS_STRING.equals(textValue)) {
  1148. return TRUE;
  1149. }
  1150. if (FALSE_AS_STRING.equals(textValue)) {
  1151. return FALSE;
  1152. }
  1153. throw new IllegalStateException("Unexpected boolean cached formula value '"
  1154. + textValue + "'.");
  1155. case STRING:
  1156. // fall-through
  1157. case NUMERIC:
  1158. // fall-through
  1159. case ERROR:
  1160. return textValue;
  1161. default:
  1162. throw new IllegalStateException("Unexpected formula result type (" + cellType + ")");
  1163. }
  1164. }
  1165. @Override
  1166. public CellRangeAddress getArrayFormulaRange() {
  1167. XSSFCell cell = getSheet().getFirstCellInArrayFormula(this);
  1168. if (cell == null) {
  1169. throw new IllegalStateException("Cell " + getReference()
  1170. + " is not part of an array formula.");
  1171. }
  1172. String formulaRef = cell._cell.getF().getRef();
  1173. return CellRangeAddress.valueOf(formulaRef);
  1174. }
  1175. @Override
  1176. public boolean isPartOfArrayFormulaGroup() {
  1177. return getSheet().isCellInArrayFormulaContext(this);
  1178. }
  1179. /**
  1180. * The purpose of this method is to validate the cell state prior to modification
  1181. *
  1182. * @see #notifyArrayFormulaChanging()
  1183. */
  1184. void notifyArrayFormulaChanging(String msg){
  1185. if(isPartOfArrayFormulaGroup()){
  1186. CellRangeAddress cra = getArrayFormulaRange();
  1187. if(cra.getNumberOfCells() > 1) {
  1188. throw new IllegalStateException(msg);
  1189. }
  1190. //un-register the single-cell array formula from the parent XSSFSheet
  1191. getRow().getSheet().removeArrayFormula(this);
  1192. }
  1193. }
  1194. /**
  1195. * Called when this cell is modified.
  1196. * <p>
  1197. * The purpose of this method is to validate the cell state prior to modification.
  1198. * </p>
  1199. *
  1200. * @see #setCellType(CellType)
  1201. * @see #setCellFormula(String)
  1202. * @see XSSFRow#removeCell(org.apache.poi.ss.usermodel.Cell)
  1203. * @see org.apache.poi.xssf.usermodel.XSSFSheet#removeRow(org.apache.poi.ss.usermodel.Row)
  1204. * @see org.apache.poi.xssf.usermodel.XSSFSheet#shiftRows(int, int, int)
  1205. * @see org.apache.poi.xssf.usermodel.XSSFSheet#addMergedRegion(org.apache.poi.ss.util.CellRangeAddress)
  1206. * @throws IllegalStateException if modification is not allowed
  1207. */
  1208. void notifyArrayFormulaChanging(){
  1209. CellReference ref = new CellReference(this);
  1210. String msg = "Cell "+ref.formatAsString()+" is part of a multi-cell array formula. " +
  1211. "You cannot change part of an array.";
  1212. notifyArrayFormulaChanging(msg);
  1213. }
  1214. }