Translate a column index into an Excel Column Name

前端 未结 15 2309
花落未央
花落未央 2020-11-27 20:41

Given a columns\' index, how can you get an Excel column name?

The problem is trickier than it sounds because it\'s not just base-26. The columns

15条回答
  •  庸人自扰
    2020-11-27 21:03

    The answer I came up with is to get a little recursive. This code is in VB.Net:

    Function ColumnName(ByVal index As Integer) As String
            Static chars() As Char = {"A"c, "B"c, "C"c, "D"c, "E"c, "F"c, "G"c, "H"c, "I"c, "J"c, "K"c, "L"c, "M"c, "N"c, "O"c, "P"c, "Q"c, "R"c, "S"c, "T"c, "U"c, "V"c, "W"c, "X"c, "Y"c, "Z"c}
    
            index -= 1 ''//adjust so it matches 0-indexed array rather than 1-indexed column
    
            Dim quotient As Integer = index \ 26 ''//normal / operator rounds. \ does integer division, which truncates
            If quotient > 0 Then
                   ColumnName = ColumnName(quotient) & chars(index Mod 26)
            Else
                   ColumnName = chars(index Mod 26)
            End If
    End Function
    

    And in C#:

    string ColumnName(int index)
    {
        index -= 1; //adjust so it matches 0-indexed array rather than 1-indexed column
    
        int quotient = index / 26;
        if (quotient > 0)
            return ColumnName(quotient) + chars[index % 26].ToString();
        else
            return chars[index % 26].ToString();
    }
    private char[] chars = new char[] {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
    

    The only downside it that it uses 1-indexed columns rather than 0-indexed.

提交回复
热议问题