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

Posted yysbolg

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }
}

 

以上是关于Java 导出 Excel 列号数字与字母互相转换工具的主要内容,如果未能解决你的问题,请参考以下文章

Python实现excel的列名称转数字、26进制(A-Z)与10进制互相转换

excel 如何自动生成32位的大写字母跟数字组合的随机序列,类似于验证码的那种随机的

Excel的列数如何用数字表示?

excel表格中,横向复制拖动的时候怎么才能让字母别跟着变啊

码蹄集 - MT2051 · excel的烦恼

Excel地址