将列索引转换为 Excel 列名 [英] Translate a column index into an Excel Column Name
本文介绍了将列索引转换为 Excel 列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个列的索引,如何获得 Excel 列名?
Given a columns' index, how can you get an Excel column name?
这个问题比听起来更棘手,因为它不只是 base-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.
免责声明:这是我不久前完成的一些代码,今天它再次出现在我的桌面上.我认为值得在这里发布一个预先回答的问题.
推荐答案
我想出的答案是稍微递归.此代码在 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# 中:
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-indexed 列而不是 0-indexed.
The only downside it that it uses 1-indexed columns rather than 0-indexed.
这篇关于将列索引转换为 Excel 列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文