excel导入数据源格式化


// 判断字符串是否属于数字类型 整数、小数、负数、百分数
public boolean isNumber(String str) {
	Pattern pattern  = Pattern.compile("(\\d*\\.\\d*)|(\\d*)|(\\d*\\.\\d*\\%)|(\\d*\\%)| (\\-\\d*\\.\\d*)|(\\-\\d*)|(\\-\\d*\\.\\d*\\%)|(\\-\\d*\\%)");
	Matcher matcher = pattern.matcher(str);
	return matcher.matches();
}

public <T> T toNumber(Object obj, Class<T> clazz) {
	return toNumber(obj,null, clazz);
}

public <T> T toNumber(Object obj,Object defaltValue, Class<T> clazz) {
	return toNumber(obj,defaltValue,false,false, clazz);
}

/**
* @param obj
* @param defaltValue 默认值,传递参数时如果出现错误返回默认值,入非数字类型,空字符,对异常不做处理正常抛出
* @param isperCent 判断传入值是否设置为百分数,及无论传入值是整数还是百分数,都会处理后除100, true 是,false 否
* @param lessOne 在设置百分数后,判断当前值是否小于1 ,若小于1 则为实际值,不除100; true 不除100; false 不做处理,正常除100
* @param clazz 参数返回值类型
*
*/
public <T> toNumber(Object obj,Object defaltValue,Boolean isperCent, Boolean lessOne, Class<T> clazz) {
	if(Objects.isNull(obj)||Strings.isNullOrEmpty(obj.toString)) {
		return (T) defaltValue;
	}
	String str = obj.toString;
	str = str.trim();
	if(isNumber(str)) {
		int per = str.indexOf("%");
		if(per == -1&& !isperCent) {
			if(Integer.class.equals(clazz)) {
				try{
					return (T) new Integer(str);
				} catch (Exception e) {
					if(e instanceof NumberFormatException) {
						if(new Long(str) > Integer.MAX_VALUE) {
							throw e;
						} else {
							return (T) new Integer(Double.valueOf(str).intValue())
						}
					} else {
						return (T) defaltValue;
					}
				}
			}else if (Float.class.equals(clazz)) {
				return (T) new Float(str);
			}else if (BigDecimal.class.equals(clazz)) {
				return (T) new BigDecimal(str);
			}else if (Double.class.equals(clazz)) {
				return (T) new Double(str);
			}else if (Long.class.equals(clazz)) {
				try{
					return (T) new Long(str);
				} catch (Exception e) {
					if(e instanceof NumberFormatException) {
						if(new BigDecimal(str).compareTo(new BigDecimal(Long.MAX_VALUE)) > 0) {
							throw e;
						} else {
							return (T) new Integer(Double.valueOf(str).intValue())
						}
					} else{
						throw e;
					}
				}
			}
		} else{
			if(per>-1) {
				str = str.substring(0,per);
			}
			if (Float.class.equals(clazz)) {
				Float percent = Float.parseFloat(str);
				if(percent1< 1&& lessOne) {
					return (T) percent
				}
				percent = percent/100;
				return (T) percent;
			}else if (BigDecimal.class.equals(clazz)) {
				BigDecimal percent = new BigDecimal(str);
				if(percent1.compareTo(new BigDecimal(1))< 0&& lessOne) {
					return (T) percent
				}
				percent =  percent.devide(new BigDecimal(100));
				return (T) percent;
			}else if (Double.class.equals(clazz)) {
				Double percent = Double.parseFloat(str);
				if(percent1< 1&& lessOne) {
					return (T) percent
				}
				percent = percent/100;
				return (T) percent;
			}
		}	
	}
	return (T) defaltValue;
}

你可能感兴趣的:(java实用方法整合,java,excel)