2015-08-12 11 views
5

Próbuję zapisać dane do plików Excela za pomocą vb.net. Więc to moja funkcja, która przekształca kolumnę liczb w kolumny z literą excela.Konwertowanie liczb na kolumnę z literą Excela vb.net

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 

Funkcja działa poprawnie z dowolnymi innymi numerami.

Przykładowo

  • 1 => A
  • 2 => B
  • ...
  • 26 => Z
  • 27 => AA
  • ...
  • 51 => AY
  • 52 => t (I tu jest, gdy zaczyna się iść źle) Przypuszczalnie zwraca AZ, ale zwróciło t.

Nie mogłem ustalić, w której części popełniłem błąd. Czy ktoś może mi pomóc lub pokazać mi, jak zakodować odpowiednią funkcję przekształcania liczb w kolumny literowe excel przy użyciu vb.net.

Odpowiedz

6

To powinno zrobić, co chcesz.

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

Dziękuję. To działa dla mnie. – bill

0

W logice jest kilka wad, druga klauzula nie jest wymagana, a operacje powinny być zerowe.

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 
+0

Dziękuję. Podany kod nie działa dla 26, który powinien zwrócić Z. Ale zwraca AA – bill

+0

@bill thanks. Kod jest naprawiony. – wdosanjos

0

To będzie pracować do 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 

Na marginesie, można zapisywać pliki XLSX bezpośrednio z EPPlus poprzez .Net. Możesz użyć notacji dla kolumn, jeśli chcesz, lub możesz użyć liczb.

+0

Dzięki. Ale szukam ogólniejszej zasady przekształcania liczb w doskonałe kolumny – bill