Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

HSSFCell.java 44KB

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