将数字转换为Excel字母列的VB.NET代码

9

我正在尝试使用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个回答

11

这应该可以做到你想要的。

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

逻辑上有一些缺陷,第二个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

谢谢。您提供的代码在输入26时无法正常工作,应该返回Z,但它返回了AA。 - bill

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 文件。如果你愿意,你可以使用字母表示列,也可以使用数字。


谢谢。但我正在寻找将数字转换为Excel列的更一般规则。 - bill

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接