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

前端 未结 30 2090
鱼传尺愫
鱼传尺愫 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:59

    I'm surprised all of the solutions so far contain either iteration or recursion.

    Here's my solution that runs in constant time (no loops). This solution works for all possible Excel columns and checks that the input can be turned into an Excel column. Possible columns are in the range [A, XFD] or [1, 16384]. (This is dependent on your version of Excel)

    private static string Turn(uint col)
    {
        if (col < 1 || col > 16384) //Excel columns are one-based (one = 'A')
            throw new ArgumentException("col must be >= 1 and <= 16384");
    
        if (col <= 26) //one character
            return ((char)(col + 'A' - 1)).ToString();
    
        else if (col <= 702) //two characters
        {
            char firstChar = (char)((int)((col - 1) / 26) + 'A' - 1);
            char secondChar = (char)(col % 26 + 'A' - 1);
    
            if (secondChar == '@') //Excel is one-based, but modulo operations are zero-based
                secondChar = 'Z'; //convert one-based to zero-based
    
            return string.Format("{0}{1}", firstChar, secondChar);
        }
    
        else //three characters
        {
            char firstChar = (char)((int)((col - 1) / 702) + 'A' - 1);
            char secondChar = (char)((col - 1) / 26 % 26 + 'A' - 1);
            char thirdChar = (char)(col % 26 + 'A' - 1);
    
            if (thirdChar == '@') //Excel is one-based, but modulo operations are zero-based
                thirdChar = 'Z'; //convert one-based to zero-based
    
            return string.Format("{0}{1}{2}", firstChar, secondChar, thirdChar);
        }
    }
    

提交回复
热议问题