2
此代碼以文本文件作爲輸入,並將每行存儲在字符串數組中,循環遍歷每行並檢查條件並最終填充數組。使用vb.net將數組映射到Excel
當我嘗試通過excel對象庫的.range
方法將此一維數組轉換爲excel列時,它將使用數組的第一個值(即array(0))填充範圍內的所有單元格。
sr = openFileDialog1.FileName()
If (sr IsNot Nothing) Then
Dim alltextlines() As String = IO.File.ReadAllLines(sr)
Dim name As String
Dim isvalid As Boolean
Dim tempstr() As String
Dim count As Integer = 0
For Each myLine In alltextlines
ReDim Preserve tempstr(count)
If myLine.Contains(">") And myLine.Contains(" sds dsd") Then
isvalid = Integer.TryParse((Microsoft.VisualBasic.Mid(Microsoft.VisualBasic.LTrim(myLine), 3, 1)), 0)
If isvalid Then
name = Microsoft.VisualBasic.Left(Microsoft.VisualBasic.LTrim(myLine), 5)
Else
name = Microsoft.VisualBasic.Left(Microsoft.VisualBasic.LTrim(myLine), 7)
End If
tempstr(count) = name
count = count + 1
End If
Next
Dim message As String = String.Join("..", tempstr)
MsgBox(message)
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
'Start a new workbook in Excel.
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
oSheet = oBook.Worksheets(1)
oSheet.Range("A1").Value = "SiteNames"
oSheet.Range("A1:B1").Font.Bold = True
oSheet.Range("A2").Resize(tempstr.Length).Value = tempstr
oSheet = Nothing
oBook = Nothing
oExcel.Quit()
oExcel = Nothing
GC.Collect()
Else
MsgBox("TEXT FILE IS EMPTY", MsgBoxStyle.Critical, "Error")
End If
End If
End Sub
感謝您說明了這一點。 – user1687139