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

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

    After looking at all the supplied Versions here, i descided to do one myself, using recursion.

    Here is my vb.net Version:

    Function CL(ByVal x As Integer) As String
        If x >= 1 And x <= 26 Then
            CL = Chr(x + 64)
        Else
            CL = CL((x - x Mod 26) / 26) & Chr((x Mod 26) + 1 + 64)
        End If
    End Function
    
    0 讨论(0)
  • 2020-11-22 00:59

    This is the question all others as well as Google redirect to so I'm posting this here.

    Many of these answers are correct but too cumbersome for simple situations such as when you don't have over 26 columns. If you have any doubt whether you might go into double character columns then ignore this answer, but if you're sure you won't, then you could do it as simple as this in C#:

    public static char ColIndexToLetter(short index)
    {
        if (index < 0 || index > 25) throw new ArgumentException("Index must be between 0 and 25.");
        return (char)('A' + index);
    }
    

    Heck, if you're confident about what you're passing in you could even remove the validation and use this inline:

    (char)('A' + index)
    

    This will be very similar in many languages so you can adapt it as needed.

    Again, only use this if you're 100% sure you won't have more than 26 columns.

    0 讨论(0)
  • 2020-11-22 01:00

    Refining the original solution (in C#):

    public static class ExcelHelper
    {
        private static Dictionary<UInt16, String> l_DictionaryOfColumns;
    
        public static ExcelHelper() {
            l_DictionaryOfColumns = new Dictionary<ushort, string>(256);
        }
    
        public static String GetExcelColumnName(UInt16 l_Column)
        {
            UInt16 l_ColumnCopy = l_Column;
            String l_Chars = "0ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            String l_rVal = "";
            UInt16 l_Char;
    
    
            if (l_DictionaryOfColumns.ContainsKey(l_Column) == true)
            {
                l_rVal = l_DictionaryOfColumns[l_Column];
            }
            else
            {
                while (l_ColumnCopy > 26)
                {
                    l_Char = l_ColumnCopy % 26;
                    if (l_Char == 0)
                        l_Char = 26;
    
                    l_ColumnCopy = (l_ColumnCopy - l_Char) / 26;
                    l_rVal = l_Chars[l_Char] + l_rVal;
                }
                if (l_ColumnCopy != 0)
                    l_rVal = l_Chars[l_ColumnCopy] + l_rVal;
    
                l_DictionaryOfColumns.ContainsKey(l_Column) = l_rVal;
            }
    
            return l_rVal;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 01:00

    I'm trying to do the same thing in Java... I've wrote following code:

    private String getExcelColumnName(int columnNumber) {
    
        int dividend = columnNumber;
        String columnName = "";
        int modulo;
    
        while (dividend > 0)
        {
            modulo = (dividend - 1) % 26;
    
            char val = Character.valueOf((char)(65 + modulo));
    
            columnName += val;
    
            dividend = (int)((dividend - modulo) / 26);
        } 
    
        return columnName;
    }
    

    Now once I ran it with columnNumber = 29, it gives me the result = "CA" (instead of "AC") any comments what I'm missing? I know I can reverse it by StringBuilder.... But looking at the Graham's answer, I'm little confused....

    0 讨论(0)
  • 2020-11-22 01:01

    Just throwing in a simple two-line C# implementation using recursion, because all the answers here seem far more complicated than necessary.

    /// <summary>
    /// Gets the column letter(s) corresponding to the given column number.
    /// </summary>
    /// <param name="column">The one-based column index. Must be greater than zero.</param>
    /// <returns>The desired column letter, or an empty string if the column number was invalid.</returns>
    public static string GetColumnLetter(int column) {
        if (column < 1) return String.Empty;
        return GetColumnLetter((column - 1) / 26) + (char)('A' + (column - 1) % 26);
    }
    
    0 讨论(0)
  • 2020-11-22 01:02

    You might need conversion both ways, e.g from Excel column adress like AAZ to integer and from any integer to Excel. The two methods below will do just that. Assumes 1 based indexing, first element in your "arrays" are element number 1. No limits on size here, so you can use adresses like ERROR and that would be column number 2613824 ...

    public static string ColumnAdress(int col)
    {
      if (col <= 26) { 
        return Convert.ToChar(col + 64).ToString();
      }
      int div = col / 26;
      int mod = col % 26;
      if (mod == 0) {mod = 26;div--;}
      return ColumnAdress(div) + ColumnAdress(mod);
    }
    
    public static int ColumnNumber(string colAdress)
    {
      int[] digits = new int[colAdress.Length];
      for (int i = 0; i < colAdress.Length; ++i)
      {
        digits[i] = Convert.ToInt32(colAdress[i]) - 64;
      }
      int mul=1;int res=0;
      for (int pos = digits.Length - 1; pos >= 0; --pos)
      {
        res += digits[pos] * mul;
        mul *= 26;
      }
      return res;
    }
    
    0 讨论(0)
提交回复
热议问题