2010-10-20 39 views
0

我想知道如何獲得excel單元名稱,例如如果我通過RowNumber和ColumnNumber 那麼函數應該返回我excel單元格名稱,如「A1」。如何在asp.net中使用RowNumber和ColumnNumber來獲取excel名稱?

可能嗎?

我使用的是我在codeplex上找到的ExcelWrapper。

+0

這個問題很相似:http://stackoverflow.com/questions/837155/fastest-function-to-generate-excel-column-letters-in-c – barrowc 2010-10-21 00:05:58

+0

非常感謝。 – 2010-10-21 08:35:42

回答

0

這是從那裏我得到了回答 Translate a column index into an Excel Column Name

,並回答鏈接從該鏈接如下:

,我想出了是得到一點遞歸的答案。此代碼是在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索引。

相關問題