java之POI获取Excel单元格各种类型的值

POI获取Excel单元格各种类型的值

使用POI读取Excel表格数据时,因为表格数据可能会存在多种格式的数据,因此读取时需要注意!

	//获取单元格各类型值,返回字符串类型
	public static String getCellValueByCell(Cell cell) {
		//判断是否为null或空串
		if (cell==null || cell.toString().trim().equals("")) {
			return "";
		}
		String cellValue = "";
		int cellType=cell.getCellType();
		switch (cellType) {
			case Cell.CELL_TYPE_NUMERIC: // 数字
				short format = cell.getCellStyle().getDataFormat();
				if (DateUtil.isCellDateFormatted(cell)) {
					SimpleDateFormat sdf = null;
					if (format == 20 || format == 32) {
						sdf = new SimpleDateFormat("HH:mm");
					} else if (format == 14 || format == 31 || format == 57 || format == 58) {
						// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
						sdf = new SimpleDateFormat("yyyy-MM-dd");
						double value = cell.getNumericCellValue();
						Date date = DateUtil.getJavaDate(value);
						cellValue = sdf.format(date);
					}else {// 日期
						sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					}
					try {
						cellValue = sdf.format(cell.getDateCellValue());// 日期
					} catch (Exception e) {
						try {
							throw new Exception("exception on get date data !".concat(e.toString()));
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}finally{
						sdf = null;
					}
				}  else {
					BigDecimal bd = new BigDecimal(cell.getNumericCellValue());
					cellValue = bd.toPlainString();// 数值 用BigDecimal包装再获取plainString,可以防止获取到科学计数值
				}
				break;
			case Cell.CELL_TYPE_STRING: // 字符串
				cellValue = cell.getStringCellValue();
				break;
			case Cell.CELL_TYPE_BOOLEAN: // Boolean
				cellValue = cell.getBooleanCellValue()+"";;
				break;
			case Cell.CELL_TYPE_FORMULA: // 公式
				cellValue = cell.getCellFormula();
				break;
			default:
				cellValue = "";
				break;
		}
		//返回单元格值并去除首尾空格和去除空格
		return cellValue.trim().replace(" ","");
	}
  • 9
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值