将列索引转换为Excel列名称 [英] Translate a column index into an Excel Column Name
问题描述
问题比听起来更棘手,因为它只是基于26的不。列不会像正常数字一样包装。即使 Microsoft支持示例也不会扩展到ZZZ之外。
免责声明:这是我已经做了一些代码,今天再次遇到我的桌面。我认为这是值得在这里发布的一个预先回答的问题。
我想出的是得到一点递归。这个代码在VB.Net中:
函数ColumnName(ByVal index As Integer)As String
静态字符()作为Char = {Ac,Bc,Cc,Dc,Ec,Fc,Gc,Hc,Ic, Jc,Kc,Lc,Mc,Nc,Oc,Pc,Qc,Rc,Sc, TcUcVcWcXcYcZc}
index - = 1调整它匹配0索引数组而不是1索引列
Dim商为整数=索引\ 26'/正常/运算符轮。 \做整数除法,截断
如果商> 0然后
ColumnName = ColumnName(商)& chars(index Mod 26)
Else
ColumnName = chars(index Mod 26)
End If
End Function
在C#中:
string ColumnName(int index)
{
index - = 1; //调整,使其与0索引数组匹配,而不是1索引列
int quotient = index / 26;
if(商> 0)
返回ColumnName(商)+ chars [index%26] .ToString();
else
返回chars [index%26] .ToString();
}
private char [] chars = new char [] {'A','B','C','D','E','F','G' ''''''''''''''''''''''''''''''''''' 'U','V','W','X','Y','Z'};
它使用1索引列而不是0索引的唯一缺点。
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 don't wrap over like normal digits would. Even the Microsoft Support Example doesn't scale beyond ZZZ.
Disclaimer: This is some code I had done a while back, and it came across my desktop again today. I thought it was worthy of posting here as a pre-answered question.
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.
这篇关于将列索引转换为Excel列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!