How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

前端 未结 30 2078
鱼传尺愫
鱼传尺愫 2020-11-22 00:35

How do you convert a numerical number to an Excel column name in C# without using automation getting the value directly from Excel.

Excel 2007 has a possible range o

30条回答
  •  爱一瞬间的悲伤
    2020-11-22 00:57

    I wanted to throw in my static class I use, for interoping between col index and col Label. I use a modified accepted answer for my ColumnLabel Method

    public static class Extensions
    {
        public static string ColumnLabel(this int col)
        {
            var dividend = col;
            var columnLabel = string.Empty;
            int modulo;
    
            while (dividend > 0)
            {
                modulo = (dividend - 1) % 26;
                columnLabel = Convert.ToChar(65 + modulo).ToString() + columnLabel;
                dividend = (int)((dividend - modulo) / 26);
            } 
    
            return columnLabel;
        }
        public static int ColumnIndex(this string colLabel)
        {
            // "AD" (1 * 26^1) + (4 * 26^0) ...
            var colIndex = 0;
            for(int ind = 0, pow = colLabel.Count()-1; ind < colLabel.Count(); ++ind, --pow)
            {
                var cVal = Convert.ToInt32(colLabel[ind]) - 64; //col A is index 1
                colIndex += cVal * ((int)Math.Pow(26, pow));
            }
            return colIndex;
        }
    }
    

    Use this like...

    30.ColumnLabel(); // "AD"
    "AD".ColumnIndex(); // 30
    

提交回复
热议问题