首页 文章

将数字转换为Excel Letter列vb.net

提问于
浏览
6

我正在尝试使用vb.net将数据写入excel文件 . 所以我的函数将数字列转换为excel字母列 .

Public Function ConvertToLetter(ByRef iCol As Integer) As String

    Dim Reminder_Part As Integer = iCol Mod 26
    Dim Integer_Part As Integer = Int(iCol / 26)

    If Integer_Part = 0 Then
        ConvertToLetter = Chr(Reminder_Part + 64)
    ElseIf Integer_Part > 0 And Reminder_Part <> 0 Then
        ConvertToLetter = Chr(Integer_Part + 64) + Chr(Reminder_Part + 64)
    ElseIf Integer_Part > 0 And Reminder_Part = 0 Then
        ConvertToLetter = Chr(Integer_Part * 26 + 64)
    End If


End Function

该功能适用于任何其他数字 .

例如,

  • 1 => A.

  • 2 => B.

  • ......

  • 26 => Z.

  • 27 => AA

  • ......

  • 51 => AY

  • 52 => t(这是它开始出错的时候)假设返回AZ,但它返回了t .

我无法弄清楚我犯了什么错误 . 有人可以帮我或者告诉我如何编写使用vb.net将数字转换为excel字母列的正确功能 .

3 回答

  • 0

    这应该做你想要的 .

    Private Function GetExcelColumnName(columnNumber As Integer) As String
        Dim dividend As Integer = columnNumber
        Dim columnName As String = String.Empty
        Dim modulo As Integer
    
        While dividend > 0
           modulo = (dividend - 1) Mod 26
           columnName = Convert.ToChar(65 + modulo).ToString() & columnName
           dividend = CInt((dividend - modulo) / 26)
       End While
    
       Return columnName
    End Function
    
  • 0

    这将最多工作52 .

    Public Function ConvertToLetterA(ByRef iCol As Integer) As String
    
            Select Case iCol
                Case 1 To 26
                    Return Chr(iCol + 64)
    
                Case 27 To 52
                    Return "A" & Chr(iCol - 26 + 64)
    
            End Select
    
    End Function
    

    另外,您可以通过.Net直接使用EPPlus编写XLSX文件 . 如果您愿意,可以使用字母表示法,或者您可以使用数字 .

  • 8

    逻辑中存在一些缺陷,第二个else子句不是必需的,操作应该基于零 .

    Public Function ConvertToLetter(ByRef iCol As Integer) As String
        Dim col As Integer = iCol - 1
        Dim Reminder_Part As Integer = col Mod 26
        Dim Integer_Part As Integer = Int(col / 26)
    
        If Integer_Part = 0 Then
            ConvertToLetter = Chr(Reminder_Part + 65)
        Else
            ConvertToLetter = Chr(Integer_Part + 64) + Chr(Reminder_Part + 65)
        End If
    
    
    End Function
    

相关问题