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

前端 未结 30 2077
鱼传尺愫
鱼传尺愫 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 01:02

    Same implementaion in Java

    public String getExcelColumnName (int columnNumber) 
        {     
            int dividend = columnNumber;   
            int i;
            String columnName = "";     
            int modulo;     
            while (dividend > 0)     
            {        
                modulo = (dividend - 1) % 26;         
                i = 65 + modulo;
                columnName = new Character((char)i).toString() + columnName;        
                dividend = (int)((dividend - modulo) / 26);    
            }       
            return columnName; 
        }  
    
    0 讨论(0)
  • These my codes to convert specific number (index start from 1) to Excel Column.

        public static string NumberToExcelColumn(uint number)
        {
            uint originalNumber = number;
    
            uint numChars = 1;
            while (Math.Pow(26, numChars) < number)
            {
                numChars++;
    
                if (Math.Pow(26, numChars) + 26 >= number)
                {
                    break;
                }               
            }
    
            string toRet = "";
            uint lastValue = 0;
    
            do
            {
                number -= lastValue;
    
                double powerVal = Math.Pow(26, numChars - 1);
                byte thisCharIdx = (byte)Math.Truncate((columnNumber - 1) / powerVal);
                lastValue = (int)powerVal * thisCharIdx;
    
                if (numChars - 2 >= 0)
                {
                    double powerVal_next = Math.Pow(26, numChars - 2);
                    byte thisCharIdx_next = (byte)Math.Truncate((columnNumber - lastValue - 1) / powerVal_next);
                    int lastValue_next = (int)Math.Pow(26, numChars - 2) * thisCharIdx_next;
    
                    if (thisCharIdx_next == 0 && lastValue_next == 0 && powerVal_next == 26)
                    {
                        thisCharIdx--;
                        lastValue = (int)powerVal * thisCharIdx;
                    }
                }
    
                toRet += (char)((byte)'A' + thisCharIdx + ((numChars > 1) ? -1 : 0));
    
                numChars--;
            } while (numChars > 0);
    
            return toRet;
        }
    

    My Unit Test:

        [TestMethod]
        public void Test()
        {
            Assert.AreEqual("A", NumberToExcelColumn(1));
            Assert.AreEqual("Z", NumberToExcelColumn(26));
            Assert.AreEqual("AA", NumberToExcelColumn(27));
            Assert.AreEqual("AO", NumberToExcelColumn(41));
            Assert.AreEqual("AZ", NumberToExcelColumn(52));
            Assert.AreEqual("BA", NumberToExcelColumn(53));
            Assert.AreEqual("ZZ", NumberToExcelColumn(702));
            Assert.AreEqual("AAA", NumberToExcelColumn(703));
            Assert.AreEqual("ABC", NumberToExcelColumn(731));
            Assert.AreEqual("ACQ", NumberToExcelColumn(771));
            Assert.AreEqual("AYZ", NumberToExcelColumn(1352));
            Assert.AreEqual("AZA", NumberToExcelColumn(1353));
            Assert.AreEqual("AZB", NumberToExcelColumn(1354));
            Assert.AreEqual("BAA", NumberToExcelColumn(1379));
            Assert.AreEqual("CNU", NumberToExcelColumn(2413));
            Assert.AreEqual("GCM", NumberToExcelColumn(4823));
            Assert.AreEqual("MSR", NumberToExcelColumn(9300));
            Assert.AreEqual("OMB", NumberToExcelColumn(10480));
            Assert.AreEqual("ULV", NumberToExcelColumn(14530));
            Assert.AreEqual("XFD", NumberToExcelColumn(16384));
        }
    
    0 讨论(0)
  • 2020-11-22 01:06

    A little late to the game, but here's the code I use (in C#):

    private static readonly string _Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static int ColumnNameParse(string value)
    {
        // assumes value.Length is [1,3]
        // assumes value is uppercase
        var digits = value.PadLeft(3).Select(x => _Alphabet.IndexOf(x));
        return digits.Aggregate(0, (current, index) => (current * 26) + (index + 1));
    }
    
    0 讨论(0)
  • 2020-11-22 01:07

    Though I am late to the game, Graham's answer is far from being optimal. Particularly, you don't have to use the modulo, call ToString() and apply (int) cast. Considering that in most cases in C# world you would start numbering from 0, here is my revision:

    public static string GetColumnName(int index) // zero-based
    {
        const byte BASE = 'Z' - 'A' + 1;
        string name = String.Empty;
    
        do
        {
            name = Convert.ToChar('A' + index % BASE) + name;
            index = index / BASE - 1;
        }
        while (index >= 0);
    
        return name;
    }
    
    0 讨论(0)
  • 2020-11-22 01:08

    if you just want it for a cell formula without code, here's a formula for it:

    IF(COLUMN()>=26,CHAR(ROUND(COLUMN()/26,1)+64)&CHAR(MOD(COLUMN(),26)+64),CHAR(COLUMN()+64))
    
    0 讨论(0)
  • 2020-11-22 01:08

    Sorry, this is Python instead of C#, but at least the results are correct:

    def excel_column_number_to_name(column_number):
        output = ""
        index = column_number-1
        while index >= 0:
            character = chr((index%26)+ord('A'))
            output = output + character
            index = index/26 - 1
    
        return output[::-1]
    
    
    for i in xrange(1, 1024):
        print "%4d : %s" % (i, excel_column_number_to_name(i))
    

    Passed these test cases:

    • Column Number: 494286 => ABCDZ
    • Column Number: 27 => AA
    • Column Number: 52 => AZ
    0 讨论(0)
提交回复
热议问题