How to implement column self-naming from its index?

前端 未结 2 820
悲&欢浪女
悲&欢浪女 2020-12-22 08:13

I wish to be able to instantiate my Cell class while naming the cell instance with such name as \"A\", \"B\", \"C\", etc. just like in an Excel spreadsheet.

相关标签:
2条回答
  • 2020-12-22 08:52

    This function will do it for you. It is in VB.NET but I trust you'll be able to port it to C# if need be.
    I have updated the answer with the C# version of the function.

    VB.NET

    ''' <summary>Returns the Excel-style name of the column from the column index.</summary>
    ''' <param name="colIndex">The column index.</param>
    Function GetColumnName(ByVal colIndex As Integer) As String
        If colIndex < 1 Then Throw New ArgumentException("Column number must be greater or equal to 1.")
    
        Dim result As New List(Of String)
    
        'letter codes start at Chr(65)'
        Do While colIndex > 0
            'reduce the column number by 1 else the 26th column (Z) will become 0 (@) '
            'add 65 to the result and find the Chr() value.                           '
            'insert the character at position 0 of the character list                 '
            'integer divide by 26 to remove the column from the stack and repeat till '
            'there are no columns in the stack.                                       '
            result.Insert(0, Chr(65 + CInt((colIndex - 1) Mod 26)))
            colIndex = (colIndex - 1) \ 26
        Loop
    
        Return String.Join("", result.ToArray)
    End Function
    

    C#

    /// <summary>Returns the Excel-style name of the column from the column index.</summary>
    /// <param name="colIndex">The column index.</param>
    static string GetColumnName(int colIndex)
    {
        if (colIndex < 1)
            throw new ArgumentException("Column number must be greater or equal to 1.");
    
        var result = new List<char>();
    
        //letter codes start at Chr(65)'
        while (colIndex > 0)
        {
            //reduce the column number by 1 else the 26th column (Z) will become 0 (@) 
            //add 65 to the result and find the Chr() value.
            //insert the character at position 0 of the char list
            //integer divide the column index by 26 to remove the last calculated column 
            //from the stack and repeat till  there are no columns in the stack.                                       
            result.Insert(0, Microsoft.VisualBasic.Strings.Chr(65 + Convert.ToInt32((colIndex - 1) % 26)));
            colIndex = (int)((colIndex-1)/ 26);
        }
    
        return new string(result.ToArray());
    }
    

    I tested this up to column index 1000 and it worked without fail. I hope you find it useful.

    0 讨论(0)
  • 2020-12-22 09:13

    Here is this. Translate a column index into an Excel Column Name

    Shouldn't be to hard to make it recursive and give you exactly what you need. I hope this helps.

    0 讨论(0)
提交回复
热议问题