【发布时间】:2012-09-21 07:48:11
【问题描述】:
我需要阅读 xls 或 xlsx 表。 我成功地阅读了工作表,但它返回十进制值而不是字符串(例如:对于 3 - 它返回 3.0)。 我需要按原样读取单元格值。 所以我需要作为字符串返回
【问题讨论】:
标签: java apache-poi xls xlsx
我需要阅读 xls 或 xlsx 表。 我成功地阅读了工作表,但它返回十进制值而不是字符串(例如:对于 3 - 它返回 3.0)。 我需要按原样读取单元格值。 所以我需要作为字符串返回
【问题讨论】:
标签: java apache-poi xls xlsx
POI 为您提供 Excel 存储在文件中的确切值。通常,如果您在 Excel 单元格中写入数字,Excel 会将其存储为带格式的数字。如果您需要,POI 支持为您进行格式化(大多数人不这样做 - 他们希望将数字作为数字,以便他们可以使用它们)
您要查找的课程是DataFormatter。您的代码将类似于
DataFormatter fmt = new DataFormatter();
for (Row r : sheet) {
for (Cell c : r) {
CellReference cr = new CellRefence(c);
System.out.println("Cell " + cr.formatAsString() + " is " +
fmt.formatCellValue(c) );
}
}
【讨论】:
//use this method for getting values from excel.It might help u.
private String getCellValue(Cell cell) {
if (cell == null) {
return null;
}
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
return cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return cell.getNumericCellValue() + "";
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return cell.getBooleanCellValue() + "";
}else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
return cell.getStringCellValue();
}else if(cell.getCellType() == Cell.CELL_TYPE_ERROR){
return cell.getErrorCellValue() + "";
}
else {
return null;
}
}
【讨论】:
使用 switch 和 case 这样的代码:
switch (cell.getCellType()) {
case STRING:
String c = cell.getStringCellValue();
break;
case NUMERIC:
int n = (int) cell.getNumericCellValue();
break;
case BOOLEAN:
boolean b = cell.getBooleanCellValue();
break;
default :
}
【讨论】: