电子表格一行中单元格的高级表现形式。有三个实现类分别是HSSFCELL
,XSSFCELL
和SXSSFCELL
:
除了公式外,单元格值内容是强类型的。如,一个string类型的单元格你不能放入数字,反之亦然。
【1】单元格的获取
单元格下标索引从 0 开始。
① 获取行中第一个有效的单元格
为空则返回 -1;
short firstCellNum = row.getFirstCellNum();
② 获取行中最后一个有效的单元格
short lastCellNum = row.getLastCellNum();
③ 获取行中有效的单元格的数量
int physicalNumberOfCells = row.getPhysicalNumberOfCells();
gets the number of defined cells (NOT number of cells in the actual row!).
That is to say if only columns 0,4,5 have values then there would be 3 not 6.
④ 获取单元格类型 V3.15
该种方式在3.15版本后过时。
int cellType = cell.getCellType();
cellType 编码与值对应如下:
_NONE(-1):未知类型,
NUMERIC(0):数字类型,包括整数,小数和日期,
STRING(1):字符串类型,
FORMULA(2):公式类型,
BLANK(3):空白类型,
BOOLEAN(4):布尔类型,
ERROR(5):错误类型;
⑤ 获取单元格类型
获取cellTypeEnum,根据属性获取不同类型的单元格值:
CellType cellTypeEnum = cell.getCellTypeEnum();
switch (cellTypeEnum) {
case _NONE:
System.out.println("this cell type is undefined..");
break;
case NUMERIC:
double numericCellValue = cell.getNumericCellValue();
// Date dateCellValue = cell.getDateCellValue();
break;
case STRING:
String stringCellValue = cell.getStringCellValue();
// HSSFRichTextString richStringCellValue = cell.getRichStringCellValue();
break;
case FORMULA:
break;
case BLANK:
System.out.println("this cell is empty..");
break;
case BOOLEAN:
boolean booleanCellValue = cell.getBooleanCellValue();
break;
case ERROR:
byte errorCellValue = cell.getErrorCellValue();
break;
default:
break;
}
其中,日期
和RichTextString
获取方法说明如下:
-
①
cell.getDateCellValue()
注释:获取单元格的值作为一个date,如果是string抛出异常,如果是空的返回null,可以参考HSSFDataFormatter 了解Excel如何格式化date为string。 -
②
cell.getRichStringCellValue()
注释:获取cell的值,格式为string,如果是numeric 抛出异常,如果是空则返回空字符串。
获取单元格的值并以String格式返回,参考实例如下:
/**
* 获取单元格的数据,暂时不支持公式
*/
public static String getCellValue(Cell cell) {
if (cell == null) {
return null;
}
CellType cellType = cell.getCellTypeEnum();
String cellValue = "";
if (cell == null || cell.toString().trim().equals("")) {
return null;
} else if (cellType == CellType.STRING) {
cellValue = cell.getStringCellValue().trim();
return cellValue = StringUtils.isEmpty(cellValue) ? "" : cellValue;
} else if (cellType == CellType.NUMERIC) {
cellValue = new DecimalFormat("#.######").format(cell.getNumericCellValue());
return cellValue;
} else if (cellType == CellType.BOOLEAN) {
cellValue = String.valueOf(cell.getBooleanCellValue());
return cellValue;
} else {
return null;
}
}
⑥ 获取单元格的批注内容
HSSFCell cell = row.getCell(1);
HSSFComment cellComment = cell.getCellComment();
HSSFRichTextString string = cellComment.getString();
⑦ 为单元格设置值
如下图所示,根据不同类型为单元格设置相应值:
【2】单元格的移动
① 移动单元格到一个新列中
目标单元格一定不存在,否则报异常。
row.moveCell(cell,newColumn;
示例如下:
row.moveCell(cell,(short) 5);
第六列已经存在单元格,故抛异常。改为移动到第11列:
row.moveCell(cell,(short)10);
此时原单元格为null!对其操作将报空指针。
② 移除单元格
移除后,原单元格将为null。如,移除行中第二个单元格:
HSSFCell cell = row.getCell(1);
row.removeCell(cell);