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

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