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

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