Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

XSSFCell.java 44KB

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