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

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