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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  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.Cell;
  41. import org.apache.poi.ss.usermodel.CellStyle;
  42. import org.apache.poi.ss.usermodel.Comment;
  43. import org.apache.poi.ss.usermodel.FormulaError;
  44. import org.apache.poi.ss.usermodel.Hyperlink;
  45. import org.apache.poi.ss.usermodel.RichTextString;
  46. import org.apache.poi.ss.util.CellAddress;
  47. import org.apache.poi.ss.util.CellRangeAddress;
  48. import org.apache.poi.ss.util.CellReference;
  49. import org.apache.poi.ss.util.NumberToTextConverter;
  50. import org.apache.poi.util.LocaleUtil;
  51. /**
  52. * High level representation of a cell in a row of a spreadsheet.
  53. * Cells can be numeric, formula-based or string-based (text). The cell type
  54. * specifies this. String cells cannot contain numbers and numeric cells cannot
  55. * contain strings (at least according to our model). Client apps should do the
  56. * conversions themselves. Formula cells have the formula string, as well as
  57. * the formula result, which can be numeric or string.
  58. * <p>
  59. * Cells should have their number (0 based) before being added to a row. Only
  60. * cells that have values should be added.
  61. * <p>
  62. */
  63. public class HSSFCell implements Cell {
  64. private static final String FILE_FORMAT_NAME = "BIFF8";
  65. /**
  66. * The maximum number of columns in BIFF8
  67. */
  68. public static final int LAST_COLUMN_NUMBER = SpreadsheetVersion.EXCEL97.getLastColumnIndex(); // 2^8 - 1
  69. private static final String LAST_COLUMN_NAME = SpreadsheetVersion.EXCEL97.getLastColumnName();
  70. public final static short ENCODING_UNCHANGED = -1;
  71. public final static short ENCODING_COMPRESSED_UNICODE = 0;
  72. public final static short ENCODING_UTF_16 = 1;
  73. private final HSSFWorkbook _book;
  74. private final HSSFSheet _sheet;
  75. private int _cellType;
  76. private HSSFRichTextString _stringValue;
  77. private CellValueRecordInterface _record;
  78. private HSSFComment _comment;
  79. /**
  80. * Creates new Cell - Should only be called by HSSFRow. This creates a cell
  81. * from scratch.
  82. * <p>
  83. * When the cell is initially created it is set to CELL_TYPE_BLANK. Cell types
  84. * can be changed/overwritten by calling setCellValue with the appropriate
  85. * type as a parameter although conversions from one type to another may be
  86. * prohibited.
  87. *
  88. * @param book - Workbook record of the workbook containing this cell
  89. * @param sheet - Sheet record of the sheet containing this cell
  90. * @param row - the row of this cell
  91. * @param col - the column for this cell
  92. *
  93. * @see org.apache.poi.hssf.usermodel.HSSFRow#createCell(short)
  94. */
  95. protected HSSFCell(HSSFWorkbook book, HSSFSheet sheet, int row, short col)
  96. {
  97. checkBounds(col);
  98. _stringValue = null;
  99. _book = book;
  100. _sheet = sheet;
  101. // Relying on the fact that by default the cellType is set to 0 which
  102. // is different to CELL_TYPE_BLANK hence the following method call correctly
  103. // creates a new blank cell.
  104. short xfindex = sheet.getSheet().getXFIndexForColAt(col);
  105. setCellType(CELL_TYPE_BLANK, false, row, col,xfindex);
  106. }
  107. /**
  108. * Returns the HSSFSheet this cell belongs to
  109. *
  110. * @return the HSSFSheet that owns this cell
  111. */
  112. public HSSFSheet getSheet() {
  113. return _sheet;
  114. }
  115. /**
  116. * Returns the HSSFRow this cell belongs to
  117. *
  118. * @return the HSSFRow that owns this cell
  119. */
  120. public HSSFRow getRow() {
  121. int rowIndex = getRowIndex();
  122. return _sheet.getRow(rowIndex);
  123. }
  124. /**
  125. * Creates new Cell - Should only be called by HSSFRow. This creates a cell
  126. * from scratch.
  127. *
  128. * @param book - Workbook record of the workbook containing this cell
  129. * @param sheet - Sheet record of the sheet containing this cell
  130. * @param row - the row of this cell
  131. * @param col - the column for this cell
  132. * @param type - CELL_TYPE_NUMERIC, CELL_TYPE_STRING, CELL_TYPE_FORMULA, CELL_TYPE_BLANK,
  133. * CELL_TYPE_BOOLEAN, CELL_TYPE_ERROR
  134. * Type of cell
  135. * @see org.apache.poi.hssf.usermodel.HSSFRow#createCell(short,int)
  136. */
  137. protected HSSFCell(HSSFWorkbook book, HSSFSheet sheet, int row, short col,
  138. int type)
  139. {
  140. checkBounds(col);
  141. _cellType = -1; // 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 CELL_TYPE_STRING :
  165. _stringValue = new HSSFRichTextString(book.getWorkbook(), (LabelSSTRecord ) cval);
  166. break;
  167. case CELL_TYPE_BLANK :
  168. break;
  169. case CELL_TYPE_FORMULA :
  170. _stringValue=new HSSFRichTextString(((FormulaRecordAggregate) cval).getStringValue());
  171. break;
  172. }
  173. }
  174. /**
  175. * used internally -- given a cell value record, figure out its type
  176. */
  177. private static int determineType(CellValueRecordInterface cval) {
  178. if (cval instanceof FormulaRecordAggregate) {
  179. return HSSFCell.CELL_TYPE_FORMULA;
  180. }
  181. // all others are plain BIFF records
  182. Record record = ( Record ) cval;
  183. switch (record.getSid()) {
  184. case NumberRecord.sid : return HSSFCell.CELL_TYPE_NUMERIC;
  185. case BlankRecord.sid : return HSSFCell.CELL_TYPE_BLANK;
  186. case LabelSSTRecord.sid : return HSSFCell.CELL_TYPE_STRING;
  187. case BoolErrRecord.sid :
  188. BoolErrRecord boolErrRecord = ( BoolErrRecord ) record;
  189. return boolErrRecord.isBoolean()
  190. ? HSSFCell.CELL_TYPE_BOOLEAN
  191. : HSSFCell.CELL_TYPE_ERROR;
  192. }
  193. throw new RuntimeException("Bad cell value rec (" + cval.getClass().getName() + ")");
  194. }
  195. /**
  196. * Returns the Workbook that this Cell is bound to
  197. */
  198. protected InternalWorkbook getBoundWorkbook() {
  199. return _book.getWorkbook();
  200. }
  201. /**
  202. * @return the (zero based) index of the row containing this cell
  203. */
  204. @Override
  205. public int getRowIndex() {
  206. return _record.getRow();
  207. }
  208. /**
  209. * Updates the cell record's idea of what
  210. * column it belongs in (0 based)
  211. * @param num the new cell number
  212. */
  213. protected void updateCellNum(short num)
  214. {
  215. _record.setColumn(num);
  216. }
  217. @Override
  218. public int getColumnIndex() {
  219. return _record.getColumn() & 0xFFFF;
  220. }
  221. /**
  222. * {@inheritDoc}
  223. */
  224. @Override
  225. public CellAddress getAddress() {
  226. return new CellAddress(this);
  227. }
  228. /**
  229. * Set the cells type (numeric, formula or string).
  230. * If the cell currently contains a value, the value will
  231. * be converted to match the new type, if possible.
  232. * @see #CELL_TYPE_NUMERIC
  233. * @see #CELL_TYPE_STRING
  234. * @see #CELL_TYPE_FORMULA
  235. * @see #CELL_TYPE_BLANK
  236. * @see #CELL_TYPE_BOOLEAN
  237. * @see #CELL_TYPE_ERROR
  238. */
  239. public void setCellType(int cellType) {
  240. notifyFormulaChanging();
  241. if(isPartOfArrayFormulaGroup()){
  242. notifyArrayFormulaChanging();
  243. }
  244. int row=_record.getRow();
  245. short col=_record.getColumn();
  246. short styleIndex=_record.getXFIndex();
  247. setCellType(cellType, true, row, col, styleIndex);
  248. }
  249. /**
  250. * sets the cell type. The setValue flag indicates whether to bother about
  251. * trying to preserve the current value in the new record if one is created.
  252. * <p>
  253. * The @see #setCellValue method will call this method with false in setValue
  254. * since it will overwrite the cell value later
  255. *
  256. */
  257. private void setCellType(int cellType, boolean setValue, int row,short col, short styleIndex)
  258. {
  259. if (cellType > CELL_TYPE_ERROR)
  260. {
  261. throw new RuntimeException("I have no idea what type that is!");
  262. }
  263. switch (cellType)
  264. {
  265. case CELL_TYPE_FORMULA :
  266. FormulaRecordAggregate frec;
  267. if (cellType != _cellType) {
  268. frec = _sheet.getSheet().getRowsAggregate().createFormula(row, col);
  269. } else {
  270. frec = (FormulaRecordAggregate) _record;
  271. frec.setRow(row);
  272. frec.setColumn(col);
  273. }
  274. if (setValue)
  275. {
  276. frec.getFormulaRecord().setValue(getNumericCellValue());
  277. }
  278. frec.setXFIndex(styleIndex);
  279. _record = frec;
  280. break;
  281. case CELL_TYPE_NUMERIC :
  282. NumberRecord nrec = null;
  283. if (cellType != _cellType)
  284. {
  285. nrec = new NumberRecord();
  286. }
  287. else
  288. {
  289. nrec = ( NumberRecord ) _record;
  290. }
  291. nrec.setColumn(col);
  292. if (setValue)
  293. {
  294. nrec.setValue(getNumericCellValue());
  295. }
  296. nrec.setXFIndex(styleIndex);
  297. nrec.setRow(row);
  298. _record = nrec;
  299. break;
  300. case CELL_TYPE_STRING :
  301. LabelSSTRecord lrec;
  302. if (cellType == _cellType) {
  303. lrec = (LabelSSTRecord) _record;
  304. } else {
  305. lrec = new LabelSSTRecord();
  306. lrec.setColumn(col);
  307. lrec.setRow(row);
  308. lrec.setXFIndex(styleIndex);
  309. }
  310. if (setValue) {
  311. String str = convertCellValueToString();
  312. if(str == null) {
  313. // bug 55668: don't try to store null-string when formula
  314. // results in empty/null value
  315. setCellType(CELL_TYPE_BLANK, false, row, col, styleIndex);
  316. return;
  317. } else {
  318. int sstIndex = _book.getWorkbook().addSSTString(new UnicodeString(str));
  319. lrec.setSSTIndex(sstIndex);
  320. UnicodeString us = _book.getWorkbook().getSSTString(sstIndex);
  321. _stringValue = new HSSFRichTextString();
  322. _stringValue.setUnicodeString(us);
  323. }
  324. }
  325. _record = lrec;
  326. break;
  327. case CELL_TYPE_BLANK :
  328. BlankRecord brec = null;
  329. if (cellType != _cellType)
  330. {
  331. brec = new BlankRecord();
  332. }
  333. else
  334. {
  335. brec = ( BlankRecord ) _record;
  336. }
  337. brec.setColumn(col);
  338. // During construction the cellStyle may be null for a Blank cell.
  339. brec.setXFIndex(styleIndex);
  340. brec.setRow(row);
  341. _record = brec;
  342. break;
  343. case CELL_TYPE_BOOLEAN :
  344. BoolErrRecord boolRec = null;
  345. if (cellType != _cellType)
  346. {
  347. boolRec = new BoolErrRecord();
  348. }
  349. else
  350. {
  351. boolRec = ( BoolErrRecord ) _record;
  352. }
  353. boolRec.setColumn(col);
  354. if (setValue)
  355. {
  356. boolRec.setValue(convertCellValueToBoolean());
  357. }
  358. boolRec.setXFIndex(styleIndex);
  359. boolRec.setRow(row);
  360. _record = boolRec;
  361. break;
  362. case CELL_TYPE_ERROR :
  363. BoolErrRecord errRec = null;
  364. if (cellType != _cellType)
  365. {
  366. errRec = new BoolErrRecord();
  367. }
  368. else
  369. {
  370. errRec = ( BoolErrRecord ) _record;
  371. }
  372. errRec.setColumn(col);
  373. if (setValue)
  374. {
  375. errRec.setValue(FormulaError.VALUE.getCode());
  376. }
  377. errRec.setXFIndex(styleIndex);
  378. errRec.setRow(row);
  379. _record = errRec;
  380. break;
  381. }
  382. if (cellType != _cellType &&
  383. _cellType!=-1 ) // Special Value to indicate an uninitialized Cell
  384. {
  385. _sheet.getSheet().replaceValueRecord(_record);
  386. }
  387. _cellType = cellType;
  388. }
  389. /**
  390. * get the cells type (numeric, formula or string)
  391. * @see #CELL_TYPE_STRING
  392. * @see #CELL_TYPE_NUMERIC
  393. * @see #CELL_TYPE_FORMULA
  394. * @see #CELL_TYPE_BOOLEAN
  395. * @see #CELL_TYPE_ERROR
  396. */
  397. public int getCellType()
  398. {
  399. return _cellType;
  400. }
  401. /**
  402. * set a numeric value for the cell
  403. *
  404. * @param value the numeric value to set this cell to. For formulas we'll set the
  405. * precalculated value, for numerics we'll set its value. For other types we
  406. * will change the cell to a numeric cell and set its value.
  407. */
  408. public void setCellValue(double value) {
  409. if(Double.isInfinite(value)) {
  410. // Excel does not support positive/negative infinities,
  411. // rather, it gives a #DIV/0! error in these cases.
  412. setCellErrorValue(FormulaError.DIV0.getCode());
  413. } else if (Double.isNaN(value)){
  414. // Excel does not support Not-a-Number (NaN),
  415. // instead it immediately generates a #NUM! error.
  416. setCellErrorValue(FormulaError.NUM.getCode());
  417. } else {
  418. int row=_record.getRow();
  419. short col=_record.getColumn();
  420. short styleIndex=_record.getXFIndex();
  421. switch (_cellType) {
  422. default:
  423. setCellType(CELL_TYPE_NUMERIC, false, row, col, styleIndex);
  424. case CELL_TYPE_NUMERIC:
  425. (( NumberRecord ) _record).setValue(value);
  426. break;
  427. case CELL_TYPE_FORMULA:
  428. ((FormulaRecordAggregate)_record).setCachedDoubleResult(value);
  429. break;
  430. }
  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. int row=_record.getRow();
  487. short col=_record.getColumn();
  488. short styleIndex=_record.getXFIndex();
  489. if (value == null)
  490. {
  491. notifyFormulaChanging();
  492. setCellType(CELL_TYPE_BLANK, false, row, col, styleIndex);
  493. return;
  494. }
  495. if(value.length() > SpreadsheetVersion.EXCEL97.getMaxTextLength()){
  496. throw new IllegalArgumentException("The maximum length of cell contents (text) is 32,767 characters");
  497. }
  498. if (_cellType == CELL_TYPE_FORMULA) {
  499. // Set the 'pre-evaluated result' for the formula
  500. // note - formulas do not preserve text formatting.
  501. FormulaRecordAggregate fr = (FormulaRecordAggregate) _record;
  502. fr.setCachedStringResult(value.getString());
  503. // Update our local cache to the un-formatted version
  504. _stringValue = new HSSFRichTextString(value.getString());
  505. // All done
  506. return;
  507. }
  508. // If we get here, we're not dealing with a formula,
  509. // so handle things as a normal rich text cell
  510. if (_cellType != CELL_TYPE_STRING) {
  511. setCellType(CELL_TYPE_STRING, false, row, col, styleIndex);
  512. }
  513. int index = 0;
  514. HSSFRichTextString hvalue = (HSSFRichTextString) value;
  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 throw an exception
  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 throw an exception
  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 FormulaError.forInt(((BoolErrRecord)_record).getErrorValue()).getString();
  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 FormulaError.forInt(fr.getCachedErrorValue()).getString();
  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. * <p>Set the style for the cell. The style should be an HSSFCellStyle created/retreived from
  807. * the HSSFWorkbook.</p>
  808. *
  809. * <p>To change the style of a cell without affecting other cells that use the same style,
  810. * use {@link org.apache.poi.ss.util.CellUtil#setCellStyleProperties(org.apache.poi.ss.usermodel.Cell, java.util.Map)}</p>
  811. *
  812. * @param style reference contained in the workbook
  813. * @see org.apache.poi.hssf.usermodel.HSSFWorkbook#createCellStyle()
  814. * @see org.apache.poi.hssf.usermodel.HSSFWorkbook#getCellStyleAt(int)
  815. */
  816. public void setCellStyle(CellStyle style) {
  817. setCellStyle( (HSSFCellStyle)style );
  818. }
  819. public void setCellStyle(HSSFCellStyle style) {
  820. // A style of null means resetting back to the default style
  821. if (style == null) {
  822. _record.setXFIndex((short)0xf);
  823. return;
  824. }
  825. // Verify the style really does belong to our workbook
  826. style.verifyBelongsToWorkbook(_book);
  827. short styleIndex;
  828. if(style.getUserStyleName() != null) {
  829. styleIndex = applyUserCellStyle(style);
  830. } else {
  831. styleIndex = style.getIndex();
  832. }
  833. // Change our cell record to use this style
  834. _record.setXFIndex(styleIndex);
  835. }
  836. /**
  837. * get the style for the cell. This is a reference to a cell style contained in the workbook
  838. * object.
  839. * @see org.apache.poi.hssf.usermodel.HSSFWorkbook#getCellStyleAt(int)
  840. */
  841. public HSSFCellStyle getCellStyle()
  842. {
  843. short styleIndex=_record.getXFIndex();
  844. ExtendedFormatRecord xf = _book.getWorkbook().getExFormatAt(styleIndex);
  845. return new HSSFCellStyle(styleIndex, xf, _book);
  846. }
  847. /**
  848. * Should only be used by HSSFSheet and friends. Returns the low level CellValueRecordInterface record
  849. *
  850. * @return CellValueRecordInterface representing the cell via the low level api.
  851. */
  852. protected CellValueRecordInterface getCellValueRecord()
  853. {
  854. return _record;
  855. }
  856. /**
  857. * @throws RuntimeException if the bounds are exceeded.
  858. */
  859. private static void checkBounds(int cellIndex) {
  860. if (cellIndex < 0 || cellIndex > LAST_COLUMN_NUMBER) {
  861. throw new IllegalArgumentException("Invalid column index (" + cellIndex
  862. + "). Allowable column range for " + FILE_FORMAT_NAME + " is (0.."
  863. + LAST_COLUMN_NUMBER + ") or ('A'..'" + LAST_COLUMN_NAME + "')");
  864. }
  865. }
  866. /**
  867. * {@inheritDoc}
  868. */
  869. @Override
  870. public void setAsActiveCell()
  871. {
  872. int row=_record.getRow();
  873. short col=_record.getColumn();
  874. _sheet.getSheet().setActiveCellRow(row);
  875. _sheet.getSheet().setActiveCellCol(col);
  876. }
  877. /**
  878. * Returns a string representation of the cell
  879. *
  880. * This method returns a simple representation,
  881. * anything more complex should be in user code, with
  882. * knowledge of the semantics of the sheet being processed.
  883. *
  884. * Formula cells return the formula string,
  885. * rather than the formula result.
  886. * Dates are displayed in dd-MMM-yyyy format
  887. * Errors are displayed as #ERR&lt;errIdx&gt;
  888. */
  889. public String toString() {
  890. switch (getCellType()) {
  891. case CELL_TYPE_BLANK:
  892. return "";
  893. case CELL_TYPE_BOOLEAN:
  894. return getBooleanCellValue()?"TRUE":"FALSE";
  895. case CELL_TYPE_ERROR:
  896. return ErrorEval.getText((( BoolErrRecord ) _record).getErrorValue());
  897. case CELL_TYPE_FORMULA:
  898. return getCellFormula();
  899. case CELL_TYPE_NUMERIC:
  900. //TODO apply the dataformat for this cell
  901. if (HSSFDateUtil.isCellDateFormatted(this)) {
  902. SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", LocaleUtil.getUserLocale());
  903. sdf.setTimeZone(LocaleUtil.getUserTimeZone());
  904. return sdf.format(getDateCellValue());
  905. }
  906. return String.valueOf(getNumericCellValue());
  907. case CELL_TYPE_STRING:
  908. return getStringCellValue();
  909. default:
  910. return "Unknown Cell Type: " + getCellType();
  911. }
  912. }
  913. /**
  914. * Assign a comment to this cell. If the supplied
  915. * comment is null, the comment for this cell
  916. * will be removed.
  917. *
  918. * @param comment comment associated with this cell
  919. */
  920. public void setCellComment(Comment comment){
  921. if(comment == null) {
  922. removeCellComment();
  923. return;
  924. }
  925. comment.setRow(_record.getRow());
  926. comment.setColumn(_record.getColumn());
  927. _comment = (HSSFComment)comment;
  928. }
  929. /**
  930. * Returns comment associated with this cell
  931. *
  932. * @return comment associated with this cell
  933. */
  934. public HSSFComment getCellComment(){
  935. if (_comment == null) {
  936. _comment = _sheet.findCellComment(_record.getRow(), _record.getColumn());
  937. }
  938. return _comment;
  939. }
  940. /**
  941. * Removes the comment for this cell, if
  942. * there is one.
  943. * WARNING - some versions of excel will loose
  944. * all comments after performing this action!
  945. */
  946. public void removeCellComment() {
  947. HSSFComment comment = _sheet.findCellComment(_record.getRow(), _record.getColumn());
  948. _comment = null;
  949. if (null == comment){
  950. return;
  951. }
  952. _sheet.getDrawingPatriarch().removeShape(comment);
  953. }
  954. /**
  955. * @return hyperlink associated with this cell or <code>null</code> if not found
  956. */
  957. @Override
  958. public HSSFHyperlink getHyperlink(){
  959. return _sheet.getHyperlink(_record.getRow(), _record.getColumn());
  960. }
  961. /**
  962. * Assign a hyperlink to this cell. If the supplied hyperlink is null, the
  963. * hyperlink for this cell will be removed.
  964. *
  965. * @param hyperlink hyperlink associated with this cell
  966. */
  967. @Override
  968. public void setHyperlink(Hyperlink hyperlink){
  969. if (hyperlink == null) {
  970. removeHyperlink();
  971. return;
  972. }
  973. HSSFHyperlink link = (HSSFHyperlink)hyperlink;
  974. link.setFirstRow(_record.getRow());
  975. link.setLastRow(_record.getRow());
  976. link.setFirstColumn(_record.getColumn());
  977. link.setLastColumn(_record.getColumn());
  978. switch(link.getType()){
  979. case HSSFHyperlink.LINK_EMAIL:
  980. case HSSFHyperlink.LINK_URL:
  981. link.setLabel("url");
  982. break;
  983. case HSSFHyperlink.LINK_FILE:
  984. link.setLabel("file");
  985. break;
  986. case HSSFHyperlink.LINK_DOCUMENT:
  987. link.setLabel("place");
  988. break;
  989. }
  990. List<RecordBase> records = _sheet.getSheet().getRecords();
  991. int eofLoc = records.size() - 1;
  992. records.add( eofLoc, link.record );
  993. }
  994. /**
  995. * Removes the hyperlink for this cell, if there is one.
  996. */
  997. public void removeHyperlink() {
  998. for (Iterator<RecordBase> it = _sheet.getSheet().getRecords().iterator(); it.hasNext();) {
  999. RecordBase rec = it.next();
  1000. if (rec instanceof HyperlinkRecord) {
  1001. HyperlinkRecord link = (HyperlinkRecord) rec;
  1002. if (link.getFirstColumn() == _record.getColumn() && link.getFirstRow() == _record.getRow()) {
  1003. it.remove();
  1004. return;
  1005. }
  1006. }
  1007. }
  1008. }
  1009. /**
  1010. * Only valid for formula cells
  1011. * @return one of ({@link #CELL_TYPE_NUMERIC}, {@link #CELL_TYPE_STRING},
  1012. * {@link #CELL_TYPE_BOOLEAN}, {@link #CELL_TYPE_ERROR}) depending
  1013. * on the cached value of the formula
  1014. */
  1015. public int getCachedFormulaResultType() {
  1016. if (_cellType != CELL_TYPE_FORMULA) {
  1017. throw new IllegalStateException("Only formula cells have cached results");
  1018. }
  1019. return ((FormulaRecordAggregate)_record).getFormulaRecord().getCachedResultType();
  1020. }
  1021. void setCellArrayFormula(CellRangeAddress range) {
  1022. int row = _record.getRow();
  1023. short col = _record.getColumn();
  1024. short styleIndex = _record.getXFIndex();
  1025. setCellType(CELL_TYPE_FORMULA, false, row, col, styleIndex);
  1026. // Billet for formula in rec
  1027. Ptg[] ptgsForCell = {new ExpPtg(range.getFirstRow(), range.getFirstColumn())};
  1028. FormulaRecordAggregate agg = (FormulaRecordAggregate) _record;
  1029. agg.setParsedExpression(ptgsForCell);
  1030. }
  1031. public CellRangeAddress getArrayFormulaRange() {
  1032. if (_cellType != CELL_TYPE_FORMULA) {
  1033. String ref = new CellReference(this).formatAsString();
  1034. throw new IllegalStateException("Cell " + ref
  1035. + " is not part of an array formula.");
  1036. }
  1037. return ((FormulaRecordAggregate)_record).getArrayFormulaRange();
  1038. }
  1039. public boolean isPartOfArrayFormulaGroup() {
  1040. if (_cellType != CELL_TYPE_FORMULA) {
  1041. return false;
  1042. }
  1043. return ((FormulaRecordAggregate)_record).isPartOfArrayFormula();
  1044. }
  1045. /**
  1046. * The purpose of this method is to validate the cell state prior to modification
  1047. *
  1048. * @see #notifyArrayFormulaChanging()
  1049. */
  1050. void notifyArrayFormulaChanging(String msg){
  1051. CellRangeAddress cra = getArrayFormulaRange();
  1052. if(cra.getNumberOfCells() > 1) {
  1053. throw new IllegalStateException(msg);
  1054. }
  1055. //un-register the single-cell array formula from the parent XSSFSheet
  1056. getRow().getSheet().removeArrayFormula(this);
  1057. }
  1058. /**
  1059. * Called when this cell is modified.
  1060. * <p>
  1061. * The purpose of this method is to validate the cell state prior to modification.
  1062. * </p>
  1063. *
  1064. * @see #setCellType(int)
  1065. * @see #setCellFormula(String)
  1066. * @see HSSFRow#removeCell(org.apache.poi.ss.usermodel.Cell)
  1067. * @see org.apache.poi.hssf.usermodel.HSSFSheet#removeRow(org.apache.poi.ss.usermodel.Row)
  1068. * @see org.apache.poi.hssf.usermodel.HSSFSheet#shiftRows(int, int, int)
  1069. * @see org.apache.poi.hssf.usermodel.HSSFSheet#addMergedRegion(org.apache.poi.ss.util.CellRangeAddress)
  1070. * @throws IllegalStateException if modification is not allowed
  1071. */
  1072. void notifyArrayFormulaChanging(){
  1073. CellReference ref = new CellReference(this);
  1074. String msg = "Cell "+ref.formatAsString()+" is part of a multi-cell array formula. " +
  1075. "You cannot change part of an array.";
  1076. notifyArrayFormulaChanging(msg);
  1077. }
  1078. /**
  1079. * Applying a user-defined style (UDS) is special. Excel does not directly reference user-defined styles, but
  1080. * instead create a 'proxy' ExtendedFormatRecord referencing the UDS as parent.
  1081. *
  1082. * The proceudre to apply a UDS is as follows:
  1083. *
  1084. * 1. search for a ExtendedFormatRecord with parentIndex == style.getIndex()
  1085. * and xfType == ExtendedFormatRecord.XF_CELL.
  1086. * 2. if not found then create a new ExtendedFormatRecord and copy all attributes from the user-defined style
  1087. * and set the parentIndex to be style.getIndex()
  1088. * 3. return the index of the ExtendedFormatRecord, this will be assigned to the parent cell record
  1089. *
  1090. * @param style the user style to apply
  1091. *
  1092. * @return the index of a ExtendedFormatRecord record that will be referenced by the cell
  1093. */
  1094. private short applyUserCellStyle(HSSFCellStyle style){
  1095. if(style.getUserStyleName() == null) {
  1096. throw new IllegalArgumentException("Expected user-defined style");
  1097. }
  1098. InternalWorkbook iwb = _book.getWorkbook();
  1099. short userXf = -1;
  1100. int numfmt = iwb.getNumExFormats();
  1101. for(short i = 0; i < numfmt; i++){
  1102. ExtendedFormatRecord xf = iwb.getExFormatAt(i);
  1103. if(xf.getXFType() == ExtendedFormatRecord.XF_CELL && xf.getParentIndex() == style.getIndex() ){
  1104. userXf = i;
  1105. break;
  1106. }
  1107. }
  1108. short styleIndex;
  1109. if (userXf == -1){
  1110. ExtendedFormatRecord xfr = iwb.createCellXF();
  1111. xfr.cloneStyleFrom(iwb.getExFormatAt(style.getIndex()));
  1112. xfr.setIndentionOptions((short)0);
  1113. xfr.setXFType(ExtendedFormatRecord.XF_CELL);
  1114. xfr.setParentIndex(style.getIndex());
  1115. styleIndex = (short)numfmt;
  1116. } else {
  1117. styleIndex = userXf;
  1118. }
  1119. return styleIndex;
  1120. }
  1121. }