欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-28 12:19:09
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;
    }
}