1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
|
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.xssf.usermodel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.poi.hssf.record.formula.eval.ErrorEval;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.StylesSource;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
import org.apache.poi.xssf.model.SharedStringSource;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellFormula;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType;
/**
*
*/
public final class XSSFCell implements Cell {
private static final String FALSE_AS_STRING = "0";
private static final String TRUE_AS_STRING = "1";
private final CTCell cell;
private final XSSFRow row;
private int cellNum;
private SharedStringsTable sharedStringSource;
private StylesTable stylesSource;
private POILogger logger = POILogFactory.getLogger(XSSFCell.class);
public XSSFCell(XSSFRow row, CTCell cell) {
this.cell = cell;
this.row = row;
if (cell.getR() != null) {
this.cellNum = parseCellNum(cell.getR());
}
this.sharedStringSource = row.getSheet().getWorkbook().getSharedStringSource();
this.stylesSource = row.getSheet().getWorkbook().getStylesSource();
}
protected SharedStringsTable getSharedStringSource() {
return this.sharedStringSource;
}
protected StylesSource getStylesSource() {
return this.stylesSource;
}
public Sheet getSheet() {
return this.row.getSheet();
}
public boolean getBooleanCellValue() {
if (STCellType.B != cell.getT()) {
throw new NumberFormatException("You cannot get a boolean value from a non-boolean cell");
}
if (cell.isSetV()) {
return (TRUE_AS_STRING.equals(this.cell.getV()));
}
return false;
}
public Comment getCellComment() {
return row.getSheet().getCellComment(row.getRowNum(), getCellNum());
}
public String getCellFormula() {
if(this.cell.getF() == null) {
throw new NumberFormatException("You cannot get a formula from a non-formula cell");
}
return this.cell.getF().getStringValue();
}
/**
* @deprecated use {@link #getColumnIndex()}
*/
public short getCellNum() {
return (short)getColumnIndex();
}
public int getColumnIndex() {
return this.cellNum;
}
public int getRowIndex() {
return row.getRowNum();
}
public XSSFCellStyle getCellStyle() {
// Zero is the empty default
if(this.cell.getS() > 0) {
return stylesSource.getStyleAt(this.cell.getS());
}
return null;
}
public int getCellType() {
// Detecting formulas is quite pesky,
// as they don't get their type set
if(this.cell.getF() != null) {
return CELL_TYPE_FORMULA;
}
switch (this.cell.getT().intValue()) {
case STCellType.INT_B:
return CELL_TYPE_BOOLEAN;
case STCellType.INT_N:
if(!cell.isSetV()) {
// ooxml does have a separate cell type of 'blank'. A blank cell gets encoded as
// (either not present or) a numeric cell with no value set.
// The formula evaluator (and perhaps other clients of this interface) needs to
// distinguish blank values which sometimes get translated into zero and sometimes
// empty string, depending on context
return CELL_TYPE_BLANK;
}
return CELL_TYPE_NUMERIC;
case STCellType.INT_E:
return CELL_TYPE_ERROR;
case STCellType.INT_S: // String is in shared strings
case STCellType.INT_INLINE_STR: // String is inline in cell
return CELL_TYPE_STRING;
case STCellType.INT_STR:
return CELL_TYPE_FORMULA;
default:
throw new IllegalStateException("Illegal cell type: " + this.cell.getT());
}
}
public Date getDateCellValue() {
if (STCellType.N == this.cell.getT() || STCellType.STR == this.cell.getT()) {
double value = this.getNumericCellValue();
if (false /* book.isUsing1904DateWindowing() */) { // FIXME
return DateUtil.getJavaDate(value,true);
}
else {
return DateUtil.getJavaDate(value,false);
}
}
throw new NumberFormatException("You cannot get a date value from a cell of type " + this.cell.getT());
}
/**
* Returns the error message, such as #VALUE!
*/
public String getErrorCellString() {
if (STCellType.E != cell.getT()) {
throw new NumberFormatException("You cannot get a error value from a non-error cell");
}
if (this.cell.isSetV()) {
return this.cell.getV();
}
return null;
}
/**
* Returns the error type, in the same way that
* HSSFCell does. See {@link Cell} for details
*/
public byte getErrorCellValue() {
if (STCellType.E != cell.getT()) {
throw new NumberFormatException("You cannot get a error value from a non-error cell");
}
if (this.cell.isSetV()) {
String errS = this.cell.getV();
if(errS.equals(Cell.ERROR_NULL.getStringRepr())) {
return Cell.ERROR_NULL.getType();
}
if(errS.equals(Cell.ERROR_DIV0.getStringRepr())) {
return Cell.ERROR_DIV0.getType();
}
if(errS.equals(Cell.ERROR_VALUE.getStringRepr())) {
return Cell.ERROR_VALUE.getType();
}
if(errS.equals(Cell.ERROR_REF.getStringRepr())) {
return Cell.ERROR_REF.getType();
}
if(errS.equals(Cell.ERROR_NAME.getStringRepr())) {
return Cell.ERROR_NAME.getType();
}
if(errS.equals(Cell.ERROR_NUM.getStringRepr())) {
return Cell.ERROR_NUM.getType();
}
return Cell.ERROR_NA.getType();
}
return 0;
}
public double getNumericCellValue() {
if (STCellType.N != cell.getT() && STCellType.STR != cell.getT()) {
throw new NumberFormatException("You cannot get a numeric value from a non-numeric cell");
}
if (this.cell.isSetV()) {
return Double.parseDouble(this.cell.getV());
}
// else - cell is blank.
// TODO - behaviour in the case of blank cells.
// Revise spec, choose best alternative below, and comment why.
if (true) {
// returning NaN from a blank cell seems wrong
// there are a few junits which assert this behaviour, though.
return Double.NaN;
}
if (true) {
// zero is probably a more reasonable value.
return 0.0;
} else {
// or perhaps disallow reading value from blank cell.
throw new RuntimeException("You cannot get a numeric value from a blank cell");
}
// Note - it would be nice if the behaviour is consistent with getRichStringCellValue
// (i.e. whether to return empty string or throw exception).
}
public XSSFRichTextString getRichStringCellValue() {
if(this.cell.getT() == STCellType.INLINE_STR) {
if(this.cell.isSetV()) {
return new XSSFRichTextString(this.cell.getV());
} else {
return new XSSFRichTextString("");
}
}
if(this.cell.getT() == STCellType.S) {
XSSFRichTextString rt;
if(this.cell.isSetV()) {
int sRef = Integer.parseInt(this.cell.getV());
rt = new XSSFRichTextString(sharedStringSource.getEntryAt(sRef));
} else {
rt = new XSSFRichTextString("");
}
rt.setStylesTableReference(stylesSource);
return rt;
}
throw new NumberFormatException("You cannot get a string value from a non-string cell");
}
/**
* Sets this cell as the active cell for the worksheet
*/
public void setAsActiveCell() {
row.getSheet().setActiveCell(cell.getR());
}
public void setCellComment(Comment comment) {
String cellRef = new CellReference(row.getRowNum(), getCellNum()).formatAsString();
row.getSheet().setCellComment(cellRef, (XSSFComment)comment);
}
public void setCellErrorValue(byte value) {
if(value == Cell.ERROR_DIV0.getType()) {
setCellErrorValue(Cell.ERROR_DIV0);
} else if(value == Cell.ERROR_NA.getType()) {
setCellErrorValue(Cell.ERROR_NA);
} else if(value == Cell.ERROR_NAME.getType()) {
setCellErrorValue(Cell.ERROR_NAME);
} else if(value == Cell.ERROR_NULL.getType()) {
setCellErrorValue(Cell.ERROR_NULL);
} else if(value == Cell.ERROR_NUM.getType()) {
setCellErrorValue(Cell.ERROR_NUM);
} else if(value == Cell.ERROR_REF.getType()) {
setCellErrorValue(Cell.ERROR_REF);
} else if(value == Cell.ERROR_VALUE.getType()) {
setCellErrorValue(Cell.ERROR_VALUE);
} else {
logger.log(POILogger.WARN, "Unknown error type " + value + " specified, treating as #N/A");
setCellErrorValue(Cell.ERROR_NA);
}
}
public void setCellErrorValue(CELL_ERROR_TYPE errorType) {
if ((this.cell.getT() != STCellType.E) && (this.cell.getT() != STCellType.STR))
{
this.cell.setT(STCellType.E);
}
this.cell.setV( errorType.getStringRepr() );
}
public void setCellFormula(String formula) {
CTCellFormula f = CTCellFormula.Factory.newInstance();
f.setStringValue(formula);
this.cell.setF(f);
// XXX: is this correct? Should we recompute the value when the formula changes?
if (this.cell.isSetV()) {
this.cell.unsetV();
}
}
public void setCellNum(int num) {
setCellNum((short)num);
}
public void setCellNum(short num) {
checkBounds(num);
this.cellNum = num;
this.cell.setR(formatPosition());
}
protected static short parseCellNum(String r) {
r = r.split("\\d+")[0];
if (r.length() == 1) {
return (short) (r.charAt(0) - 'A');
} else {
return (short) (r.charAt(1) - 'A' + 26 * (r.charAt(0) - '@'));
}
}
protected String formatPosition() {
int col = this.getCellNum();
String result = Character.valueOf((char) (col % 26 + 'A')).toString();
if (col >= 26){
col = col / 26;
result = Character.valueOf((char) (col + '@')) + result;
}
result = result + String.valueOf(row.getRowNum() + 1);
return result;
}
public void setCellStyle(CellStyle style) {
if(style == null) {
this.cell.setS(0);
} else {
XSSFCellStyle xStyle = (XSSFCellStyle)style;
xStyle.verifyBelongsToStylesSource(
row.getSheet().getWorkbook().getStylesSource()
);
this.cell.setS(
row.getSheet().getWorkbook().getStylesSource().putStyle(xStyle)
);
}
}
/**
* set the cells type (numeric, formula or string)
* @see #CELL_TYPE_NUMERIC
* @see #CELL_TYPE_STRING
* @see #CELL_TYPE_FORMULA
* @see #CELL_TYPE_BLANK
* @see #CELL_TYPE_BOOLEAN
* @see #CELL_TYPE_ERROR
*/
public void setCellType(int cellType) {
switch (cellType) {
case CELL_TYPE_BOOLEAN:
this.cell.setT(STCellType.B);
break;
case CELL_TYPE_NUMERIC:
this.cell.setT(STCellType.N);
break;
case CELL_TYPE_ERROR:
this.cell.setT(STCellType.E);
break;
case CELL_TYPE_STRING:
this.cell.setT(STCellType.S);
break;
default:
throw new IllegalArgumentException("Illegal type: " + cellType);
}
}
public void setCellValue(double value) {
if ((this.cell.getT() != STCellType.N) && (this.cell.getT() != STCellType.STR))
{
this.cell.setT(STCellType.N);
}
this.cell.setV(String.valueOf(value));
}
/**
* set a date value for the cell. Excel treats dates as numeric so you will need to format the cell as
* a date.
*
* @param value the date value to set this cell to. For formulas we'll set the
* precalculated value, for numerics we'll set its value. For other types we
* will change the cell to a numeric cell and set its value.
*/
public void setCellValue(Date value) {
boolean date1904 = this.row.getSheet().getWorkbook().isDate1904();
setCellValue(DateUtil.getExcelDate(value, date1904));
}
/**
* set a date value for the cell. Excel treats dates as numeric so you will need to format the cell as
* a date.
*
* This will set the cell value based on the Calendar's timezone. As Excel
* does not support timezones this means that both 20:00+03:00 and
* 20:00-03:00 will be reported as the same value (20:00) even that there
* are 6 hours difference between the two times. This difference can be
* preserved by using <code>setCellValue(value.getTime())</code> which will
* automatically shift the times to the default timezone.
*
* @param value the date value to set this cell to. For formulas we'll set the
* precalculated value, for numerics we'll set its value. For othertypes we
* will change the cell to a numeric cell and set its value.
*/
public void setCellValue(Calendar value) {
boolean date1904 = this.row.getSheet().getWorkbook().isDate1904();
setCellValue( DateUtil.getExcelDate(value, date1904 ));
}
public void setCellValue(String str) {
this.setCellValue(new XSSFRichTextString(str));
}
public void setCellValue(RichTextString value) {
if(this.cell.getT() == STCellType.INLINE_STR) {
this.cell.setV(value.getString());
return;
}
if(this.cell.getT() != STCellType.S) {
this.cell.setT(STCellType.S);
}
XSSFRichTextString rt = (XSSFRichTextString)value;
rt.setStylesTableReference(stylesSource);
int sRef = sharedStringSource.addEntry(rt.getCTRst());
this.cell.setV(Integer.toString(sRef));
}
public void setCellValue(boolean value) {
if ((this.cell.getT() != STCellType.B) && (this.cell.getT() != STCellType.STR))
{
this.cell.setT(STCellType.B);
}
this.cell.setV(value ? TRUE_AS_STRING : FALSE_AS_STRING);
}
/**
* Returns a string representation of the cell
*
* This method returns a simple representation,
* anthing more complex should be in user code, with
* knowledge of the semantics of the sheet being processed.
*
* Formula cells return the formula string,
* rather than the formula result.
* Dates are displayed in dd-MMM-yyyy format
* Errors are displayed as #ERR<errIdx>
*/
public String toString() {
// return "[" + this.row.getRowNum() + "," + this.getCellNum() + "] " + this.cell.getV();
switch (getCellType()) {
case CELL_TYPE_BLANK:
return "";
case CELL_TYPE_BOOLEAN:
return getBooleanCellValue() ? "TRUE" : "FALSE";
case CELL_TYPE_ERROR:
return ErrorEval.getText(getErrorCellValue());
case CELL_TYPE_FORMULA:
return getCellFormula();
case CELL_TYPE_NUMERIC:
//TODO apply the dataformat for this cell
if (DateUtil.isCellDateFormatted(this)) {
DateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
return sdf.format(getDateCellValue());
} else {
return getNumericCellValue() + "";
}
case CELL_TYPE_STRING:
return getRichStringCellValue().toString();
default:
return "Unknown Cell Type: " + getCellType();
}
}
/**
* Returns the raw, underlying ooxml value for the cell
*/
public String getRawValue() {
return this.cell.getV();
}
/**
* @throws RuntimeException if the bounds are exceeded.
*/
private void checkBounds(int cellNum) {
if (cellNum > 255) {
throw new RuntimeException("You cannot have more than 255 columns " +
"in a given row (IV). Because Excel can't handle it");
} else if (cellNum < 0) {
throw new RuntimeException("You cannot reference columns with an index of less then 0.");
}
}
public Hyperlink getHyperlink() {
return row.getSheet().getHyperlink(row.getRowNum(), cellNum);
}
public void setHyperlink(Hyperlink hyperlink) {
XSSFHyperlink link = (XSSFHyperlink)hyperlink;
// Assign to us
link.setCellReference( new CellReference(row.getRowNum(), cellNum).formatAsString() );
// Add to the lists
row.getSheet().setCellHyperlink(link);
}
}
|