Dot-Net

將列索引轉換為 Excel 列名

  • March 8, 2022

給定列的索引,如何獲得 Excel 列名?

這個問題比聽起來更棘手,因為它不僅僅是 base-26。這些列不會像普通數字那樣環繞。甚至Microsoft 支持範例也無法擴展到 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-indexed 列而不是 0-indexed。

引用自:https://stackoverflow.com/questions/297213