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.

HSSFCell.java 44KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  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.hssf.usermodel;
  16. import java.text.SimpleDateFormat;
  17. import java.time.LocalDateTime;
  18. import java.util.Calendar;
  19. import java.util.Date;
  20. import java.util.Iterator;
  21. import java.util.List;
  22. import org.apache.poi.hssf.model.HSSFFormulaParser;
  23. import org.apache.poi.hssf.model.InternalWorkbook;
  24. import org.apache.poi.hssf.record.BlankRecord;
  25. import org.apache.poi.hssf.record.BoolErrRecord;
  26. import org.apache.poi.hssf.record.CellValueRecordInterface;
  27. import org.apache.poi.hssf.record.ExtendedFormatRecord;
  28. import org.apache.poi.hssf.record.FormulaRecord;
  29. import org.apache.poi.hssf.record.HyperlinkRecord;
  30. import org.apache.poi.hssf.record.LabelSSTRecord;
  31. import org.apache.poi.hssf.record.NumberRecord;
  32. import org.apache.poi.hssf.record.Record;
  33. import org.apache.poi.hssf.record.RecordBase;
  34. import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
  35. import org.apache.poi.hssf.record.common.UnicodeString;
  36. import org.apache.poi.ss.SpreadsheetVersion;
  37. import org.apache.poi.ss.formula.FormulaType;
  38. import org.apache.poi.ss.formula.eval.ErrorEval;
  39. import org.apache.poi.ss.formula.ptg.ExpPtg;
  40. import org.apache.poi.ss.formula.ptg.Ptg;
  41. import org.apache.poi.ss.usermodel.CellBase;
  42. import org.apache.poi.ss.usermodel.CellStyle;
  43. import org.apache.poi.ss.usermodel.CellType;
  44. import org.apache.poi.ss.usermodel.CellValue;
  45. import org.apache.poi.ss.usermodel.Comment;
  46. import org.apache.poi.ss.usermodel.DateUtil;
  47. import org.apache.poi.ss.usermodel.FormulaError;
  48. import org.apache.poi.ss.usermodel.Hyperlink;
  49. import org.apache.poi.ss.usermodel.RichTextString;
  50. import org.apache.poi.ss.util.CellRangeAddress;
  51. import org.apache.poi.ss.util.CellReference;
  52. import org.apache.poi.ss.util.NumberToTextConverter;
  53. import org.apache.poi.util.LocaleUtil;
  54. import org.apache.poi.util.Removal;
  55. /**
  56. * High level representation of a cell in a row of a spreadsheet.
  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. * Cells should have their number (0 based) before being added to a row. Only
  64. * cells that have values should be added.
  65. * <p>
  66. */
  67. public class HSSFCell extends CellBase {
  68. private static final String FILE_FORMAT_NAME = "BIFF8";
  69. /**
  70. * The maximum number of columns in BIFF8
  71. */
  72. public static final int LAST_COLUMN_NUMBER = SpreadsheetVersion.EXCEL97.getLastColumnIndex(); // 2^8 - 1
  73. private static final String LAST_COLUMN_NAME = SpreadsheetVersion.EXCEL97.getLastColumnName();
  74. public static final short ENCODING_UNCHANGED = -1;
  75. public static final short ENCODING_COMPRESSED_UNICODE = 0;
  76. public static final short ENCODING_UTF_16 = 1;
  77. private final HSSFWorkbook _book;
  78. private final HSSFSheet _sheet;
  79. private CellType _cellType;
  80. private HSSFRichTextString _stringValue;
  81. private CellValueRecordInterface _record;
  82. private HSSFComment _comment;
  83. /**
  84. * Creates new Cell - Should only be called by HSSFRow. This creates a cell
  85. * from scratch.
  86. * <p>
  87. * When the cell is initially created it is set to {@link CellType#BLANK}. Cell types
  88. * can be changed/overwritten by calling setCellValue with the appropriate
  89. * type as a parameter although conversions from one type to another may be
  90. * prohibited.
  91. *
  92. * @param book - Workbook record of the workbook containing this cell
  93. * @param sheet - Sheet record of the sheet containing this cell
  94. * @param row - the row of this cell
  95. * @param col - the column for this cell
  96. *
  97. * @see org.apache.poi.hssf.usermodel.HSSFRow#createCell(int)
  98. */
  99. protected HSSFCell(HSSFWorkbook book, HSSFSheet sheet, int row, short col)
  100. {
  101. checkBounds(col);
  102. _stringValue = null;
  103. _book = book;
  104. _sheet = sheet;
  105. // Relying on the fact that by default the cellType is set to 0 which
  106. // is different to {@link CellType#BLANK} hence the following method call correctly
  107. // creates a new blank cell.
  108. short xfindex = sheet.getSheet().getXFIndexForColAt(col);
  109. setCellType(CellType.BLANK, false, row, col,xfindex);
  110. }
  111. /**
  112. * {@inheritDoc}
  113. */
  114. @Override
  115. protected SpreadsheetVersion getSpreadsheetVersion() {
  116. return SpreadsheetVersion.EXCEL97;
  117. }
  118. /**
  119. * Returns the HSSFSheet this cell belongs to
  120. *
  121. * @return the HSSFSheet that owns this cell
  122. */
  123. public HSSFSheet getSheet() {
  124. return _sheet;
  125. }
  126. /**
  127. * Returns the HSSFRow this cell belongs to
  128. *
  129. * @return the HSSFRow that owns this cell
  130. */
  131. public HSSFRow getRow() {
  132. int rowIndex = getRowIndex();
  133. return _sheet.getRow(rowIndex);
  134. }
  135. /**
  136. * Creates new Cell - Should only be called by HSSFRow. This creates a cell
  137. * from scratch.
  138. *
  139. * @param book - Workbook record of the workbook containing this cell
  140. * @param sheet - Sheet record of the sheet containing this cell
  141. * @param row - the row of this cell
  142. * @param col - the column for this cell
  143. * @param type - Type of cell
  144. * @see org.apache.poi.hssf.usermodel.HSSFRow#createCell(int,CellType)
  145. */
  146. protected HSSFCell(HSSFWorkbook book, HSSFSheet sheet, int row, short col,
  147. CellType type)
  148. {
  149. checkBounds(col);
  150. _cellType = CellType._NONE; // Force 'setCellType' to create a first Record
  151. _stringValue = null;
  152. _book = book;
  153. _sheet = sheet;
  154. short xfindex = sheet.getSheet().getXFIndexForColAt(col);
  155. setCellType(type,false,row,col,xfindex);
  156. }
  157. /**
  158. * Creates an HSSFCell from a CellValueRecordInterface. HSSFSheet uses this when
  159. * reading in cells from an existing sheet.
  160. *
  161. * @param book - Workbook record of the workbook containing this cell
  162. * @param sheet - Sheet record of the sheet containing this cell
  163. * @param cval - the Cell Value Record we wish to represent
  164. */
  165. protected HSSFCell(HSSFWorkbook book, HSSFSheet sheet, CellValueRecordInterface cval) {
  166. _record = cval;
  167. _cellType = determineType(cval);
  168. _stringValue = null;
  169. _book = book;
  170. _sheet = sheet;
  171. switch (_cellType)
  172. {
  173. case STRING :
  174. _stringValue = new HSSFRichTextString(book.getWorkbook(), (LabelSSTRecord ) cval);
  175. break;
  176. case BLANK :
  177. break;
  178. case FORMULA :
  179. _stringValue=new HSSFRichTextString(((FormulaRecordAggregate) cval).getStringValue());
  180. break;
  181. default :
  182. break;
  183. }
  184. }
  185. /**
  186. * used internally -- given a cell value record, figure out its type
  187. */
  188. private static CellType determineType(CellValueRecordInterface cval) {
  189. if (cval instanceof FormulaRecordAggregate) {
  190. return CellType.FORMULA;
  191. }
  192. // all others are plain BIFF records
  193. Record record = ( Record ) cval;
  194. switch (record.getSid()) {
  195. case NumberRecord.sid : return CellType.NUMERIC;
  196. case BlankRecord.sid : return CellType.BLANK;
  197. case LabelSSTRecord.sid : return CellType.STRING;
  198. case BoolErrRecord.sid :
  199. BoolErrRecord boolErrRecord = ( BoolErrRecord ) record;
  200. return boolErrRecord.isBoolean()
  201. ? CellType.BOOLEAN
  202. : CellType.ERROR;
  203. }
  204. throw new RuntimeException("Bad cell value rec (" + cval.getClass().getName() + ")");
  205. }
  206. /**
  207. * Returns the Workbook that this Cell is bound to
  208. */
  209. protected InternalWorkbook getBoundWorkbook() {
  210. return _book.getWorkbook();
  211. }
  212. /**
  213. * @return the (zero based) index of the row containing this cell
  214. */
  215. @Override
  216. public int getRowIndex() {
  217. return _record.getRow();
  218. }
  219. /**
  220. * Updates the cell record's idea of what
  221. * column it belongs in (0 based)
  222. * @param num the new cell number
  223. */
  224. protected void updateCellNum(short num)
  225. {
  226. _record.setColumn(num);
  227. }
  228. @Override
  229. public int getColumnIndex() {
  230. return _record.getColumn() & 0xFFFF;
  231. }
  232. @Override
  233. protected void setCellTypeImpl(CellType cellType) {
  234. notifyFormulaChanging();
  235. int row=_record.getRow();
  236. short col=_record.getColumn();
  237. short styleIndex=_record.getXFIndex();
  238. setCellType(cellType, true, row, col, styleIndex);
  239. }
  240. /**
  241. * sets the cell type. The setValue flag indicates whether to bother about
  242. * trying to preserve the current value in the new record if one is created.
  243. * <p>
  244. * The @see #setCellValue method will call this method with false in setValue
  245. * since it will overwrite the cell value later
  246. *
  247. */
  248. private void setCellType(CellType cellType, boolean setValue, int row,short col, short styleIndex)
  249. {
  250. switch (cellType)
  251. {
  252. case FORMULA :
  253. FormulaRecordAggregate frec;
  254. if (cellType != _cellType) {
  255. frec = _sheet.getSheet().getRowsAggregate().createFormula(row, col);
  256. } else {
  257. frec = (FormulaRecordAggregate) _record;
  258. frec.setRow(row);
  259. frec.setColumn(col);
  260. }
  261. if (getCellType() == CellType.BLANK) {
  262. frec.getFormulaRecord().setValue(0);
  263. }
  264. frec.setXFIndex(styleIndex);
  265. _record = frec;
  266. break;
  267. case NUMERIC :
  268. NumberRecord nrec;
  269. if (cellType != _cellType)
  270. {
  271. nrec = new NumberRecord();
  272. }
  273. else
  274. {
  275. nrec = ( NumberRecord ) _record;
  276. }
  277. nrec.setColumn(col);
  278. if (setValue)
  279. {
  280. nrec.setValue(getNumericCellValue());
  281. }
  282. nrec.setXFIndex(styleIndex);
  283. nrec.setRow(row);
  284. _record = nrec;
  285. break;
  286. case STRING :
  287. LabelSSTRecord lrec;
  288. if (cellType == _cellType) {
  289. lrec = (LabelSSTRecord) _record;
  290. } else {
  291. lrec = new LabelSSTRecord();
  292. lrec.setColumn(col);
  293. lrec.setRow(row);
  294. lrec.setXFIndex(styleIndex);
  295. }
  296. if (setValue) {
  297. String str = convertCellValueToString();
  298. if(str == null) {
  299. // bug 55668: don't try to store null-string when formula
  300. // results in empty/null value
  301. setCellType(CellType.BLANK, false, row, col, styleIndex);
  302. return;
  303. } else {
  304. int sstIndex = _book.getWorkbook().addSSTString(new UnicodeString(str));
  305. lrec.setSSTIndex(sstIndex);
  306. UnicodeString us = _book.getWorkbook().getSSTString(sstIndex);
  307. _stringValue = new HSSFRichTextString();
  308. _stringValue.setUnicodeString(us);
  309. }
  310. }
  311. _record = lrec;
  312. break;
  313. case BLANK :
  314. BlankRecord brec;
  315. if (cellType != _cellType)
  316. {
  317. brec = new BlankRecord();
  318. }
  319. else
  320. {
  321. brec = ( BlankRecord ) _record;
  322. }
  323. brec.setColumn(col);
  324. // During construction the cellStyle may be null for a Blank cell.
  325. brec.setXFIndex(styleIndex);
  326. brec.setRow(row);
  327. _record = brec;
  328. break;
  329. case BOOLEAN :
  330. BoolErrRecord boolRec;
  331. if (cellType != _cellType)
  332. {
  333. boolRec = new BoolErrRecord();
  334. }
  335. else
  336. {
  337. boolRec = ( BoolErrRecord ) _record;
  338. }
  339. boolRec.setColumn(col);
  340. if (setValue)
  341. {
  342. boolRec.setValue(convertCellValueToBoolean());
  343. }
  344. boolRec.setXFIndex(styleIndex);
  345. boolRec.setRow(row);
  346. _record = boolRec;
  347. break;
  348. case ERROR :
  349. BoolErrRecord errRec;
  350. if (cellType != _cellType)
  351. {
  352. errRec = new BoolErrRecord();
  353. }
  354. else
  355. {
  356. errRec = ( BoolErrRecord ) _record;
  357. }
  358. errRec.setColumn(col);
  359. if (setValue)
  360. {
  361. errRec.setValue(FormulaError.VALUE.getCode());
  362. }
  363. errRec.setXFIndex(styleIndex);
  364. errRec.setRow(row);
  365. _record = errRec;
  366. break;
  367. default :
  368. throw new IllegalStateException("Invalid cell type: " + cellType);
  369. }
  370. if (cellType != _cellType &&
  371. _cellType != CellType._NONE ) // Special Value to indicate an uninitialized Cell
  372. {
  373. _sheet.getSheet().replaceValueRecord(_record);
  374. }
  375. _cellType = cellType;
  376. }
  377. /**
  378. * get the cells type (numeric, formula or string)
  379. */
  380. @Override
  381. public CellType getCellType()
  382. {
  383. return _cellType;
  384. }
  385. /**
  386. * {@inheritDoc}
  387. */
  388. @Override
  389. @SuppressWarnings("fallthrough")
  390. protected void setCellValueImpl(double value) {
  391. switch (_cellType) {
  392. default:
  393. setCellType(CellType.NUMERIC,
  394. false,
  395. _record.getRow(),
  396. _record.getColumn(),
  397. _record.getXFIndex());
  398. // fall through
  399. case NUMERIC:
  400. ((NumberRecord)_record).setValue(value);
  401. break;
  402. case FORMULA:
  403. ((FormulaRecordAggregate)_record).setCachedDoubleResult(value);
  404. break;
  405. }
  406. }
  407. /**
  408. * {@inheritDoc}
  409. *
  410. * <p>In HSSF, only the number of days is stored. The fractional part is ignored.</p>
  411. * @see DateUtil
  412. * @see org.apache.poi.ss.usermodel.DateUtil
  413. */
  414. protected void setCellValueImpl(Date value) {
  415. setCellValue(DateUtil.getExcelDate(value, _book.getWorkbook().isUsing1904DateWindowing()));
  416. }
  417. /**
  418. * {@inheritDoc}
  419. *
  420. * <p>In HSSF, only the number of days is stored. The fractional part is ignored.</p>
  421. * @see DateUtil
  422. * @see org.apache.poi.ss.usermodel.DateUtil
  423. */
  424. protected void setCellValueImpl(LocalDateTime value) {
  425. setCellValue(DateUtil.getExcelDate(value, _book.getWorkbook().isUsing1904DateWindowing()));
  426. }
  427. /**
  428. * {@inheritDoc}
  429. */
  430. @Override
  431. protected void setCellValueImpl(Calendar value) {
  432. setCellValue( DateUtil.getExcelDate(value, _book.getWorkbook().isUsing1904DateWindowing()) );
  433. }
  434. /**
  435. * {@inheritDoc}
  436. */
  437. @Override
  438. protected void setCellValueImpl(String value) {
  439. setCellValueImpl(new HSSFRichTextString(value));
  440. }
  441. /**
  442. * {@inheritDoc}
  443. */
  444. @Override
  445. protected void setCellValueImpl(RichTextString value) {
  446. if (_cellType == CellType.FORMULA) {
  447. // Set the 'pre-evaluated result' for the formula
  448. // note - formulas do not preserve text formatting.
  449. FormulaRecordAggregate fr = (FormulaRecordAggregate) _record;
  450. fr.setCachedStringResult(value.getString());
  451. // Update our local cache to the un-formatted version
  452. _stringValue = new HSSFRichTextString(value.getString());
  453. // All done
  454. return;
  455. }
  456. // If we get here, we're not dealing with a formula,
  457. // so handle things as a normal rich text cell
  458. if (_cellType != CellType.STRING) {
  459. int row=_record.getRow();
  460. short col=_record.getColumn();
  461. short styleIndex=_record.getXFIndex();
  462. setCellType(CellType.STRING, false, row, col, styleIndex);
  463. }
  464. int index;
  465. HSSFRichTextString hvalue = (HSSFRichTextString) value;
  466. UnicodeString str = hvalue.getUnicodeString();
  467. index = _book.getWorkbook().addSSTString(str);
  468. (( LabelSSTRecord ) _record).setSSTIndex(index);
  469. _stringValue = hvalue;
  470. _stringValue.setWorkbookReferences(_book.getWorkbook(), (( LabelSSTRecord ) _record));
  471. _stringValue.setUnicodeString(_book.getWorkbook().getSSTString(index));
  472. }
  473. /**
  474. * {@inheritDoc}
  475. */
  476. @Override
  477. protected void setCellFormulaImpl(String formula) {
  478. // formula cells always have a value. If the cell is blank (either initially or after removing an
  479. // array formula), set value to 0
  480. if (getValueType() == CellType.BLANK) {
  481. setCellValue(0);
  482. }
  483. assert formula != null;
  484. int row=_record.getRow();
  485. short col=_record.getColumn();
  486. short styleIndex=_record.getXFIndex();
  487. final CellValue savedValue = readValue();
  488. int sheetIndex = _book.getSheetIndex(_sheet);
  489. Ptg[] ptgs = HSSFFormulaParser.parse(formula, _book, FormulaType.CELL, sheetIndex);
  490. setCellType(CellType.FORMULA, false, row, col, styleIndex);
  491. FormulaRecordAggregate agg = (FormulaRecordAggregate) _record;
  492. FormulaRecord frec = agg.getFormulaRecord();
  493. frec.setOptions((short) 2);
  494. //only set to default if there is no extended format index already set
  495. if (agg.getXFIndex() == (short)0) {
  496. agg.setXFIndex((short) 0x0f);
  497. }
  498. agg.setParsedExpression(ptgs);
  499. restoreValue(savedValue);
  500. }
  501. private CellValue readValue() {
  502. final CellType valueType = getCellType() == CellType.FORMULA ? getCachedFormulaResultType() : getCellType();
  503. switch (valueType) {
  504. case NUMERIC:
  505. return new CellValue(getNumericCellValue());
  506. case STRING:
  507. return new CellValue(getStringCellValue());
  508. case BOOLEAN:
  509. return CellValue.valueOf(getBooleanCellValue());
  510. case ERROR:
  511. return CellValue.getError(getErrorCellValue());
  512. default:
  513. throw new IllegalStateException("Unexpected cell-type " + valueType);
  514. }
  515. }
  516. private void restoreValue(CellValue value) {
  517. switch (value.getCellType()) {
  518. case NUMERIC:
  519. setCellValue(value.getNumberValue());
  520. break;
  521. case STRING:
  522. setCellValue(value.getStringValue());
  523. break;
  524. case BOOLEAN:
  525. setCellValue(value.getBooleanValue());
  526. break;
  527. case ERROR:
  528. setCellErrorValue(FormulaError.forInt(value.getErrorValue()));
  529. break;
  530. default:
  531. throw new IllegalStateException("Unexpected cell-type " + value.getCellType() + " for cell-value: " + value);
  532. }
  533. }
  534. @Override
  535. protected void removeFormulaImpl() {
  536. assert getCellType() == CellType.FORMULA;
  537. notifyFormulaChanging();
  538. switch (getCachedFormulaResultType()) {
  539. case NUMERIC:
  540. double numericValue = ((FormulaRecordAggregate)_record).getFormulaRecord().getValue();
  541. _record = new NumberRecord();
  542. ((NumberRecord)_record).setValue(numericValue);
  543. _cellType = CellType.NUMERIC;
  544. break;
  545. case STRING:
  546. _record = new NumberRecord();
  547. ((NumberRecord)_record).setValue(0);
  548. _cellType = CellType.STRING;
  549. break;
  550. case BOOLEAN:
  551. boolean booleanValue = ((FormulaRecordAggregate)_record).getFormulaRecord().getCachedBooleanValue();
  552. _record = new BoolErrRecord();
  553. ((BoolErrRecord)_record).setValue(booleanValue);
  554. _cellType = CellType.BOOLEAN;
  555. break;
  556. case ERROR:
  557. byte errorValue = (byte) ((FormulaRecordAggregate)_record).getFormulaRecord().getCachedErrorValue();
  558. _record = new BoolErrRecord();
  559. ((BoolErrRecord)_record).setValue(errorValue);
  560. _cellType = CellType.ERROR;
  561. break;
  562. default:
  563. throw new AssertionError();
  564. }
  565. }
  566. /**
  567. * Should be called any time that a formula could potentially be deleted.
  568. * Does nothing if this cell currently does not hold a formula
  569. */
  570. private void notifyFormulaChanging() {
  571. if (_record instanceof FormulaRecordAggregate) {
  572. ((FormulaRecordAggregate)_record).notifyFormulaChanging();
  573. }
  574. }
  575. public String getCellFormula() {
  576. if (!(_record instanceof FormulaRecordAggregate)) {
  577. throw typeMismatch(CellType.FORMULA, _cellType, true);
  578. }
  579. return HSSFFormulaParser.toFormulaString(_book, ((FormulaRecordAggregate)_record).getFormulaTokens());
  580. }
  581. private static RuntimeException typeMismatch(CellType expectedTypeCode, CellType actualTypeCode, boolean isFormulaCell) {
  582. String msg = "Cannot get a " + expectedTypeCode + " value from a " + actualTypeCode
  583. + " " + (isFormulaCell ? "formula " : "") + "cell";
  584. return new IllegalStateException(msg);
  585. }
  586. private static void checkFormulaCachedValueType(CellType expectedTypeCode, FormulaRecord fr) {
  587. CellType cachedValueType = fr.getCachedResultTypeEnum();
  588. if (cachedValueType != expectedTypeCode) {
  589. throw typeMismatch(expectedTypeCode, cachedValueType, true);
  590. }
  591. }
  592. /**
  593. * Get the value of the cell as a number.
  594. * For strings we throw an exception.
  595. * For blank cells we return a 0.
  596. * See {@link HSSFDataFormatter} for turning this
  597. * number into a string similar to that which
  598. * Excel would render this number as.
  599. */
  600. public double getNumericCellValue() {
  601. switch(_cellType) {
  602. case BLANK:
  603. return 0.0;
  604. case NUMERIC:
  605. return ((NumberRecord)_record).getValue();
  606. default:
  607. throw typeMismatch(CellType.NUMERIC, _cellType, false);
  608. case FORMULA:
  609. break;
  610. }
  611. FormulaRecord fr = ((FormulaRecordAggregate)_record).getFormulaRecord();
  612. checkFormulaCachedValueType(CellType.NUMERIC, fr);
  613. return fr.getValue();
  614. }
  615. /**
  616. * Get the value of the cell as a date.
  617. * For strings we throw an exception.
  618. * For blank cells we return a null.
  619. * See {@link HSSFDataFormatter} for formatting
  620. * this date into a string similar to how excel does.
  621. */
  622. public Date getDateCellValue() {
  623. if (_cellType == CellType.BLANK) {
  624. return null;
  625. }
  626. double value = getNumericCellValue();
  627. if (_book.getWorkbook().isUsing1904DateWindowing()) {
  628. return DateUtil.getJavaDate(value, true);
  629. }
  630. return DateUtil.getJavaDate(value, false);
  631. }
  632. /**
  633. * Get the value of the cell as a LocalDateTime.
  634. * For strings we throw an exception.
  635. * For blank cells we return a null.
  636. * See {@link HSSFDataFormatter} for formatting
  637. * this date into a string similar to how excel does.
  638. */
  639. public LocalDateTime getLocalDateTimeCellValue() {
  640. if (_cellType == CellType.BLANK) {
  641. return null;
  642. }
  643. double value = getNumericCellValue();
  644. if (_book.getWorkbook().isUsing1904DateWindowing()) {
  645. return DateUtil.getLocalDateTime(value, true);
  646. }
  647. return DateUtil.getLocalDateTime(value, false);
  648. }
  649. /**
  650. * get the value of the cell as a string - for numeric cells we throw an exception.
  651. * For blank cells we return an empty string.
  652. * For formulaCells that are not string Formulas, we throw an exception
  653. */
  654. public String getStringCellValue()
  655. {
  656. HSSFRichTextString str = getRichStringCellValue();
  657. return str.getString();
  658. }
  659. /**
  660. * get the value of the cell as a string - for numeric cells we throw an exception.
  661. * For blank cells we return an empty string.
  662. * For formulaCells that are not string Formulas, we throw an exception
  663. */
  664. public HSSFRichTextString getRichStringCellValue() {
  665. switch(_cellType) {
  666. case BLANK:
  667. return new HSSFRichTextString("");
  668. case STRING:
  669. return _stringValue;
  670. default:
  671. throw typeMismatch(CellType.STRING, _cellType, false);
  672. case FORMULA:
  673. break;
  674. }
  675. FormulaRecordAggregate fra = ((FormulaRecordAggregate)_record);
  676. checkFormulaCachedValueType(CellType.STRING, fra.getFormulaRecord());
  677. String strVal = fra.getStringValue();
  678. return new HSSFRichTextString(strVal == null ? "" : strVal);
  679. }
  680. /**
  681. * set a boolean value for the cell
  682. *
  683. * @param value the boolean value to set this cell to. For formulas we'll set the
  684. * precalculated value, for booleans we'll set its value. For other types we
  685. * will change the cell to a boolean cell and set its value.
  686. */
  687. @SuppressWarnings("fallthrough")
  688. public void setCellValue(boolean value) {
  689. int row=_record.getRow();
  690. short col=_record.getColumn();
  691. short styleIndex=_record.getXFIndex();
  692. switch (_cellType) {
  693. default:
  694. setCellType(CellType.BOOLEAN, false, row, col, styleIndex);
  695. // fall through
  696. case BOOLEAN:
  697. (( BoolErrRecord ) _record).setValue(value);
  698. break;
  699. case FORMULA:
  700. ((FormulaRecordAggregate)_record).setCachedBooleanResult(value);
  701. break;
  702. }
  703. }
  704. /**
  705. * set a error value for the cell
  706. *
  707. * @param errorCode the error value to set this cell to. For formulas we'll set the
  708. * precalculated value , for errors we'll set
  709. * its value. For other types we will change the cell to an error
  710. * cell and set its value.
  711. * For error code byte, see {@link FormulaError}.
  712. * @deprecated 3.15 beta 2. Use {@link #setCellErrorValue(FormulaError)} instead.
  713. */
  714. public void setCellErrorValue(byte errorCode) {
  715. FormulaError error = FormulaError.forInt(errorCode);
  716. setCellErrorValue(error);
  717. }
  718. /**
  719. * set a error value for the cell
  720. *
  721. * @param error the error value to set this cell to. For formulas we'll set the
  722. * precalculated value , for errors we'll set
  723. * its value. For other types we will change the cell to an error
  724. * cell and set its value.
  725. */
  726. @SuppressWarnings("fallthrough")
  727. public void setCellErrorValue(FormulaError error) {
  728. int row=_record.getRow();
  729. short col=_record.getColumn();
  730. short styleIndex=_record.getXFIndex();
  731. switch (_cellType) {
  732. default:
  733. setCellType(CellType.ERROR, false, row, col, styleIndex);
  734. // fall through
  735. case ERROR:
  736. (( BoolErrRecord ) _record).setValue(error);
  737. break;
  738. case FORMULA:
  739. ((FormulaRecordAggregate)_record).setCachedErrorResult(error.getCode());
  740. break;
  741. }
  742. }
  743. /**
  744. * Chooses a new boolean value for the cell when its type is changing.<p>
  745. *
  746. * Usually the caller is calling setCellType() with the intention of calling
  747. * setCellValue(boolean) straight afterwards. This method only exists to give
  748. * the cell a somewhat reasonable value until the setCellValue() call (if at all).
  749. * TODO - perhaps a method like setCellTypeAndValue(int, Object) should be introduced to avoid this
  750. * @throws IllegalStateException if cell type cannot be converted to boolean
  751. */
  752. private boolean convertCellValueToBoolean() {
  753. switch (_cellType) {
  754. case BOOLEAN:
  755. return (( BoolErrRecord ) _record).getBooleanValue();
  756. case STRING:
  757. int sstIndex = ((LabelSSTRecord)_record).getSSTIndex();
  758. String text = _book.getWorkbook().getSSTString(sstIndex).getString();
  759. return Boolean.parseBoolean(text);
  760. case NUMERIC:
  761. return ((NumberRecord)_record).getValue() != 0;
  762. case FORMULA:
  763. // use cached formula result if it's the right type:
  764. FormulaRecord fr = ((FormulaRecordAggregate)_record).getFormulaRecord();
  765. checkFormulaCachedValueType(CellType.BOOLEAN, fr);
  766. return fr.getCachedBooleanValue();
  767. // Other cases convert to false
  768. // These choices are not well justified.
  769. case ERROR:
  770. case BLANK:
  771. return false;
  772. }
  773. throw new IllegalStateException("Unexpected cell type (" + _cellType + ")");
  774. }
  775. private String convertCellValueToString() {
  776. switch (_cellType) {
  777. case BLANK:
  778. return "";
  779. case BOOLEAN:
  780. return ((BoolErrRecord) _record).getBooleanValue() ? "TRUE" : "FALSE";
  781. case STRING:
  782. int sstIndex = ((LabelSSTRecord)_record).getSSTIndex();
  783. return _book.getWorkbook().getSSTString(sstIndex).getString();
  784. case NUMERIC:
  785. return NumberToTextConverter.toText(((NumberRecord)_record).getValue());
  786. case ERROR:
  787. return FormulaError.forInt(((BoolErrRecord)_record).getErrorValue()).getString();
  788. case FORMULA:
  789. // should really evaluate, but HSSFCell can't call HSSFFormulaEvaluator
  790. // just use cached formula result instead
  791. break;
  792. default:
  793. throw new IllegalStateException("Unexpected cell type (" + _cellType + ")");
  794. }
  795. FormulaRecordAggregate fra = ((FormulaRecordAggregate)_record);
  796. FormulaRecord fr = fra.getFormulaRecord();
  797. switch (fr.getCachedResultTypeEnum()) {
  798. case BOOLEAN:
  799. return fr.getCachedBooleanValue() ? "TRUE" : "FALSE";
  800. case STRING:
  801. return fra.getStringValue();
  802. case NUMERIC:
  803. return NumberToTextConverter.toText(fr.getValue());
  804. case ERROR:
  805. return FormulaError.forInt(fr.getCachedErrorValue()).getString();
  806. default:
  807. throw new IllegalStateException("Unexpected formula result type (" + _cellType + ")");
  808. }
  809. }
  810. /**
  811. * get the value of the cell as a boolean. For strings, numbers, and errors, we throw an exception.
  812. * For blank cells we return a false.
  813. */
  814. @Override
  815. public boolean getBooleanCellValue() {
  816. switch(_cellType) {
  817. case BLANK:
  818. return false;
  819. case BOOLEAN:
  820. return (( BoolErrRecord ) _record).getBooleanValue();
  821. case FORMULA:
  822. break;
  823. default:
  824. throw typeMismatch(CellType.BOOLEAN, _cellType, false);
  825. }
  826. FormulaRecord fr = ((FormulaRecordAggregate)_record).getFormulaRecord();
  827. checkFormulaCachedValueType(CellType.BOOLEAN, fr);
  828. return fr.getCachedBooleanValue();
  829. }
  830. /**
  831. * get the value of the cell as an error code. For strings, numbers, and booleans, we throw an exception.
  832. * For blank cells we return a 0.
  833. */
  834. @Override
  835. public byte getErrorCellValue() {
  836. switch(_cellType) {
  837. case ERROR:
  838. return (( BoolErrRecord ) _record).getErrorValue();
  839. case FORMULA:
  840. FormulaRecord fr = ((FormulaRecordAggregate)_record).getFormulaRecord();
  841. checkFormulaCachedValueType(CellType.ERROR, fr);
  842. return (byte) fr.getCachedErrorValue();
  843. default:
  844. throw typeMismatch(CellType.ERROR, _cellType, false);
  845. }
  846. }
  847. /**
  848. * <p>Set the style for the cell. The style should be an HSSFCellStyle created/retreived from
  849. * the HSSFWorkbook.</p>
  850. *
  851. * <p>To change the style of a cell without affecting other cells that use the same style,
  852. * use {@link org.apache.poi.ss.util.CellUtil#setCellStyleProperties(org.apache.poi.ss.usermodel.Cell, java.util.Map)}</p>
  853. *
  854. * @param style reference contained in the workbook
  855. * @see org.apache.poi.hssf.usermodel.HSSFWorkbook#createCellStyle()
  856. * @see org.apache.poi.hssf.usermodel.HSSFWorkbook#getCellStyleAt(int)
  857. */
  858. public void setCellStyle(CellStyle style) {
  859. setCellStyle( (HSSFCellStyle)style );
  860. }
  861. public void setCellStyle(HSSFCellStyle style) {
  862. // A style of null means resetting back to the default style
  863. if (style == null) {
  864. _record.setXFIndex((short)0xf);
  865. return;
  866. }
  867. // Verify the style really does belong to our workbook
  868. style.verifyBelongsToWorkbook(_book);
  869. short styleIndex;
  870. if(style.getUserStyleName() != null) {
  871. styleIndex = applyUserCellStyle(style);
  872. } else {
  873. styleIndex = style.getIndex();
  874. }
  875. // Change our cell record to use this style
  876. _record.setXFIndex(styleIndex);
  877. }
  878. /**
  879. * get the style for the cell. This is a reference to a cell style contained in the workbook
  880. * object.
  881. * @see org.apache.poi.hssf.usermodel.HSSFWorkbook#getCellStyleAt(int)
  882. */
  883. public HSSFCellStyle getCellStyle()
  884. {
  885. short styleIndex=_record.getXFIndex();
  886. ExtendedFormatRecord xf = _book.getWorkbook().getExFormatAt(styleIndex);
  887. return new HSSFCellStyle(styleIndex, xf, _book);
  888. }
  889. /**
  890. * Should only be used by HSSFSheet and friends. Returns the low level CellValueRecordInterface record
  891. *
  892. * @return CellValueRecordInterface representing the cell via the low level api.
  893. */
  894. protected CellValueRecordInterface getCellValueRecord()
  895. {
  896. return _record;
  897. }
  898. /**
  899. * @throws RuntimeException if the bounds are exceeded.
  900. */
  901. private static void checkBounds(int cellIndex) {
  902. if (cellIndex < 0 || cellIndex > LAST_COLUMN_NUMBER) {
  903. throw new IllegalArgumentException("Invalid column index (" + cellIndex
  904. + "). Allowable column range for " + FILE_FORMAT_NAME + " is (0.."
  905. + LAST_COLUMN_NUMBER + ") or ('A'..'" + LAST_COLUMN_NAME + "')");
  906. }
  907. }
  908. /**
  909. * {@inheritDoc}
  910. */
  911. @Override
  912. public void setAsActiveCell()
  913. {
  914. int row=_record.getRow();
  915. short col=_record.getColumn();
  916. _sheet.getSheet().setActiveCellRow(row);
  917. _sheet.getSheet().setActiveCellCol(col);
  918. }
  919. /**
  920. * Returns a string representation of the cell
  921. *
  922. * This method returns a simple representation,
  923. * anything more complex should be in user code, with
  924. * knowledge of the semantics of the sheet being processed.
  925. *
  926. * Formula cells return the formula string,
  927. * rather than the formula result.
  928. * Dates are displayed in dd-MMM-yyyy format
  929. * Errors are displayed as #ERR&lt;errIdx&gt;
  930. */
  931. public String toString() {
  932. switch (getCellType()) {
  933. case BLANK:
  934. return "";
  935. case BOOLEAN:
  936. return getBooleanCellValue()?"TRUE":"FALSE";
  937. case ERROR:
  938. return ErrorEval.getText((( BoolErrRecord ) _record).getErrorValue());
  939. case FORMULA:
  940. return getCellFormula();
  941. case NUMERIC:
  942. //TODO apply the dataformat for this cell
  943. if (DateUtil.isCellDateFormatted(this)) {
  944. SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", LocaleUtil.getUserLocale());
  945. sdf.setTimeZone(LocaleUtil.getUserTimeZone());
  946. return sdf.format(getDateCellValue());
  947. }
  948. return String.valueOf(getNumericCellValue());
  949. case STRING:
  950. return getStringCellValue();
  951. default:
  952. return "Unknown Cell Type: " + getCellType();
  953. }
  954. }
  955. /**
  956. * Assign a comment to this cell. If the supplied
  957. * comment is null, the comment for this cell
  958. * will be removed.
  959. *
  960. * @param comment comment associated with this cell
  961. */
  962. public void setCellComment(Comment comment){
  963. if(comment == null) {
  964. removeCellComment();
  965. return;
  966. }
  967. comment.setRow(_record.getRow());
  968. comment.setColumn(_record.getColumn());
  969. _comment = (HSSFComment)comment;
  970. }
  971. /**
  972. * Returns comment associated with this cell
  973. *
  974. * @return comment associated with this cell
  975. */
  976. public HSSFComment getCellComment(){
  977. if (_comment == null) {
  978. _comment = _sheet.findCellComment(_record.getRow(), _record.getColumn());
  979. }
  980. return _comment;
  981. }
  982. /**
  983. * Removes the comment for this cell, if
  984. * there is one.
  985. * WARNING - some versions of excel will loose
  986. * all comments after performing this action!
  987. */
  988. public void removeCellComment() {
  989. HSSFComment comment = _sheet.findCellComment(_record.getRow(), _record.getColumn());
  990. _comment = null;
  991. if (null == comment){
  992. return;
  993. }
  994. _sheet.getDrawingPatriarch().removeShape(comment);
  995. }
  996. /**
  997. * @return hyperlink associated with this cell or <code>null</code> if not found
  998. */
  999. @Override
  1000. public HSSFHyperlink getHyperlink(){
  1001. return _sheet.getHyperlink(_record.getRow(), _record.getColumn());
  1002. }
  1003. /**
  1004. * Assign a hyperlink to this cell. If the supplied hyperlink is null, the
  1005. * hyperlink for this cell will be removed.
  1006. *
  1007. * @param hyperlink hyperlink associated with this cell
  1008. */
  1009. @Override
  1010. public void setHyperlink(Hyperlink hyperlink){
  1011. if (hyperlink == null) {
  1012. removeHyperlink();
  1013. return;
  1014. }
  1015. HSSFHyperlink link = (HSSFHyperlink)hyperlink;
  1016. link.setFirstRow(_record.getRow());
  1017. link.setLastRow(_record.getRow());
  1018. link.setFirstColumn(_record.getColumn());
  1019. link.setLastColumn(_record.getColumn());
  1020. switch(link.getType()){
  1021. case EMAIL:
  1022. case URL:
  1023. link.setLabel("url");
  1024. break;
  1025. case FILE:
  1026. link.setLabel("file");
  1027. break;
  1028. case DOCUMENT:
  1029. link.setLabel("place");
  1030. break;
  1031. default:
  1032. break;
  1033. }
  1034. List<RecordBase> records = _sheet.getSheet().getRecords();
  1035. int eofLoc = records.size() - 1;
  1036. records.add( eofLoc, link.record );
  1037. }
  1038. /**
  1039. * Removes the hyperlink for this cell, if there is one.
  1040. */
  1041. public void removeHyperlink() {
  1042. for (Iterator<RecordBase> it = _sheet.getSheet().getRecords().iterator(); it.hasNext();) {
  1043. RecordBase rec = it.next();
  1044. if (rec instanceof HyperlinkRecord) {
  1045. HyperlinkRecord link = (HyperlinkRecord) rec;
  1046. if (link.getFirstColumn() == _record.getColumn() && link.getFirstRow() == _record.getRow()) {
  1047. it.remove();
  1048. return;
  1049. }
  1050. }
  1051. }
  1052. }
  1053. /**
  1054. * Only valid for formula cells
  1055. * @return one of ({@link CellType#NUMERIC}, {@link CellType#STRING},
  1056. * {@link CellType#BOOLEAN}, {@link CellType#ERROR}) depending
  1057. * on the cached value of the formula
  1058. *
  1059. * @since POI 4.0
  1060. */
  1061. @Override
  1062. public CellType getCachedFormulaResultType() {
  1063. if (_cellType != CellType.FORMULA) {
  1064. throw new IllegalStateException("Only formula cells have cached results");
  1065. }
  1066. return ((FormulaRecordAggregate)_record).getFormulaRecord().getCachedResultTypeEnum();
  1067. }
  1068. void setCellArrayFormula(CellRangeAddress range) {
  1069. int row = _record.getRow();
  1070. short col = _record.getColumn();
  1071. short styleIndex = _record.getXFIndex();
  1072. setCellType(CellType.FORMULA, false, row, col, styleIndex);
  1073. // Billet for formula in rec
  1074. Ptg[] ptgsForCell = {new ExpPtg(range.getFirstRow(), range.getFirstColumn())};
  1075. FormulaRecordAggregate agg = (FormulaRecordAggregate) _record;
  1076. agg.setParsedExpression(ptgsForCell);
  1077. }
  1078. public CellRangeAddress getArrayFormulaRange() {
  1079. if (_cellType != CellType.FORMULA) {
  1080. String ref = new CellReference(this).formatAsString();
  1081. throw new IllegalStateException("Cell " + ref
  1082. + " is not part of an array formula.");
  1083. }
  1084. return ((FormulaRecordAggregate)_record).getArrayFormulaRange();
  1085. }
  1086. public boolean isPartOfArrayFormulaGroup() {
  1087. return _cellType == CellType.FORMULA && ((FormulaRecordAggregate) _record).isPartOfArrayFormula();
  1088. }
  1089. /**
  1090. * Applying a user-defined style (UDS) is special. Excel does not directly reference user-defined styles, but
  1091. * instead create a 'proxy' ExtendedFormatRecord referencing the UDS as parent.
  1092. *
  1093. * The proceudre to apply a UDS is as follows:
  1094. *
  1095. * 1. search for a ExtendedFormatRecord with parentIndex == style.getIndex()
  1096. * and xfType == ExtendedFormatRecord.XF_CELL.
  1097. * 2. if not found then create a new ExtendedFormatRecord and copy all attributes from the user-defined style
  1098. * and set the parentIndex to be style.getIndex()
  1099. * 3. return the index of the ExtendedFormatRecord, this will be assigned to the parent cell record
  1100. *
  1101. * @param style the user style to apply
  1102. *
  1103. * @return the index of a ExtendedFormatRecord record that will be referenced by the cell
  1104. */
  1105. private short applyUserCellStyle(HSSFCellStyle style){
  1106. if(style.getUserStyleName() == null) {
  1107. throw new IllegalArgumentException("Expected user-defined style");
  1108. }
  1109. InternalWorkbook iwb = _book.getWorkbook();
  1110. short userXf = -1;
  1111. int numfmt = iwb.getNumExFormats();
  1112. for(short i = 0; i < numfmt; i++){
  1113. ExtendedFormatRecord xf = iwb.getExFormatAt(i);
  1114. if(xf.getXFType() == ExtendedFormatRecord.XF_CELL && xf.getParentIndex() == style.getIndex() ){
  1115. userXf = i;
  1116. break;
  1117. }
  1118. }
  1119. short styleIndex;
  1120. if (userXf == -1){
  1121. ExtendedFormatRecord xfr = iwb.createCellXF();
  1122. xfr.cloneStyleFrom(iwb.getExFormatAt(style.getIndex()));
  1123. xfr.setIndentionOptions((short)0);
  1124. xfr.setXFType(ExtendedFormatRecord.XF_CELL);
  1125. xfr.setParentIndex(style.getIndex());
  1126. styleIndex = (short)numfmt;
  1127. } else {
  1128. styleIndex = userXf;
  1129. }
  1130. return styleIndex;
  1131. }
  1132. }