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

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