.net - 将列索引转换为 Excel 列名称

标签 .net excel

给定列的索引,如何获取 Excel 列名称?

这个问题比听起来更棘手,因为它不仅仅是base-26。这些列不会像普通数字那样环绕。甚至是Microsoft Support Example无法扩展至 ZZZ 之外。

免责声明:这是我不久前完成的一些代码,今天又出现在我的桌面上。我认为值得将其作为预先回答的问题发布在这里。

最佳答案

我想出的答案是进行一点递归。此代码位于 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 索引列而不是 0 索引列。

关于.net - 将列索引转换为 Excel 列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/297213/

相关文章:

vba - 在excel中截断数据(删除前12个字符)

vba - 如何在 Excel 中生成 GUID?

.net - System.Diagnostics.EventLog - 连接到系统的设备无法运行

c# - iPhone 中使用 .NET 生成的公钥进行 RSA 加密?

c# - Entity Framework 中的 POCO 支持

c# - 排序通用列表

Excel:向 XY 图表中的数据点添加标签

excel - 格式化 lucee 电子表格时出错 : The maximum number of cell styles was exceeded

c# - 无法通过 OleDb 读取大小超过 ~1mb 的 xlsx 文件

excel - 如何在不破坏对象的情况下停止 VBA 宏