您的位置:首页 > 其它

【POI】——获得单元格的值,并转化成字符串

2016-05-26 21:34 239 查看
本篇文章分享一些在做导入导出EXCEL功能时用到的工具类的一些代码。

/**
* @param cell
* @return
*/
public static String getStringValueFromCell(Cell cell) {
SimpleDateFormat sFormat = new SimpleDateFormat("MM/dd/yyyy");
DecimalFormat decimalFormat = new DecimalFormat("#.#");
String cellValue = "";
if(cell == null) {
return cellValue;
}
else if(cell.getCellType() == Cell.CELL_TYPE_STRING) {
cellValue = cell.getStringCellValue();
}

else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
if(HSSFDateUtil.isCellDateFormatted(cell)) {
double d = cell.getNumericCellValue();
Date date = HSSFDateUtil.getJavaDate(d);
cellValue = sFormat.format(date);
}
else {
cellValue = decimalFormat.format((cell.getNumericCellValue()));
}
}
else if(cell.getCellType() == Cell.CELL_TYPE_BLANK) {
cellValue = "";
}
else if(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
cellValue = String.valueOf(cell.getBooleanCellValue());
}
else if(cell.getCellType() == Cell.CELL_TYPE_ERROR) {
cellValue = "";
}
else if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
cellValue = cell.getCellFormula().toString();
}
return cellValue;
}


如果直接使用

cell.getStringCellValue();


当单元格的格式为数字或其他格式时,这句代码就会报错,在开发时一定要注意。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: