生成类似 excel 版本号 A ,B,C,...,Z AA,AB,..,AZ ...

          生成类似 excel 版本号 A ,B,C,...,Z  AA,AB,..,AZ ...

  最近遇到一个需求:每次对一条记录进行修改或指定操作,需要生成一个历史版本,版本号需要采用类似excel表格的列号的形式,第一版本为A,第二版本为B,以此类推由A-Z,AA,AB,AC,...,AZ,ZZ,AAA-ZZZ。由于考虑到后面有根据版本号排序,根据版本号范围查询数据的需求,思考了一下,采用了数据库的版本号字段存的是数字1,2,3,4 ....分别对应A,,B,C,D ....,52对应AZ,这样的一个对应关系,查询到数据的时候把数字的版本号通过计算查询出对应的字符串版本(A,B,C...)在前台展示。如果需要根据版本号去数据库查询数据,可以根据前台传入的字符串版本号转换后再拼接参数查询,存数字最主要的是为了能更好的比较大小,下面把主要代码记录一下,大家如果有什么更好的解决方案,也可在下方留言大家一起讨论。

  

    
    /**
     * 将字符串(a-z)转换成数字
     * 按照excel表格的列号(如:a-->1,z-->26,aa->27,az-52,....)
     * @param str
     * @return
     */
    public static int str2int(String str){
		char[] array = str.toCharArray();
		int result = 0;
		for (int j = 0; j < array.length; j++) {
			result*=26;
			result+=char2int(array[j]);
		}
		return result;
	};
	
	/**
	 * 将字符转换成整数
	 * @param ch
	 * @return
	 */
	public static int char2int(char ch){
		int result = -1;
		if(ch >= 'A' && ch <= 'Z'){
			result = ch - 'A' + 1;
		}else if(ch >= 'a' && ch <= 'z'){
			result = ch - 'a' + 1;
		}
		return  result;
	}
	
	/**
	 * 将1转换成A,26转换成Z,无限往后推,对应excel表格的列
	 * @param num
	 * @return
	 */
	public static String int2Str(int num){
		String result = "";
		num = num <=0 ? 1 : num;//小于等于0是输出A
		while(num > 0){
			int m = num %26;
			if(m == 0) m = 26;
			result = (char)(m + 64) + result;
			num = (num-m)/26;
		}
		return result;
	}
	

  

posted @ 2019-05-17 15:03  追梦950  阅读(952)  评论(0编辑  收藏  举报