您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

HSSFCell.java 43KB

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