翻译一列索引到一个Excel列名索引、Excel

2023-09-02 01:26:28 作者:人走茶凉心亦寒i

由于一列的索引,你怎么能得到一个Excel列名?

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

现在的问题是棘手比它听起来,因为它的不可以只是基础-26。该列不换行过像正常的数字会。即使是 Microsoft支持例没有规模超过ZZZ。

The problem is trickier than it sounds because it's not just base-26. The columns don't wrap over like normal digits would. Even the Microsoft Support Example doesn't scale beyond ZZZ.

的免责声明:这是一些code我做了一段时间后,它今天再次在我的台式机来了。我认为这是值得张贴在这里为pre-回答问题。的

推荐答案

我想出答案是变得有点递归。这code是在VB.Net:

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

和在C#:

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'};

唯一的缺点是,它使用1索引列,而不是0索引。

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