当前位置: 移动技术网 > IT编程>开发语言>Java > Java 导出 Excel 列号数字与字母互相转换工具

Java 导出 Excel 列号数字与字母互相转换工具

2019年01月27日  | 移动技术网IT编程  | 我要评论
Java 导出 Excel 列号数字与字母互相转换工具 ...
package test;

/**
 * deal with excel column indextostr and strtoindex
 * @author 
 * @version 2015-7-8
 * @see
 */
public class excelcolumn {

    public static void main(string[] args) {
        string colstr = "aa";
        int colindex = excelcolstrtonum(colstr, colstr.length());
        system.out.println("'" + colstr + "' column index of " + colindex);

        colindex = 26;
        colstr = excelcolindextostr(colindex);
        system.out.println(colindex + " column in excel of " + colstr);

        colstr = "aaaa";
        colindex = excelcolstrtonum(colstr, colstr.length());
        system.out.println("'" + colstr + "' column index of " + colindex);

        colindex = 466948;
        colstr = excelcolindextostr(colindex);
        system.out.println(colindex + " column in excel of " + colstr);
    }

    /**
     * excel column index begin 1
     * @param colstr
     * @param length
     * @return
     */
    public static int excelcolstrtonum(string colstr, int length) {
        int num = 0;
        int result = 0;
        for(int i = 0; i < length; i++) {
            char ch = colstr.charat(length - i - 1);
            num = (int)(ch - 'a' + 1) ;
            num *= math.pow(26, i);
            result += num;
        }
        return result;
    }

    /**
     * excel column index begin 1
     * @param columnindex
     * @return
     */
    public static string excelcolindextostr(int columnindex) {
        if (columnindex <= 0) {
            return null;
        }
        string columnstr = "";
        columnindex--;
        do {
            if (columnstr.length() > 0) {
                columnindex--;
            }
            columnstr = ((char) (columnindex % 26 + (int) 'a')) + columnstr;
            columnindex = (int) ((columnindex - columnindex % 26) / 26);
        } while (columnindex > 0);
        return columnstr;
    }
}

 

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网