[英]CSV file to datagridview using list
這類似於: https : //social.msdn.microsoft.com/Forums/en-US/7b0e28b4-c1ef-49d6-8f46-11b379428052/import-from-csv-file-to-二維數組?論壇= vbgeneral
但是Cor Ligthert建議的代碼即使確實正是我所需要的也不起作用。
代碼是:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim FILE_NAME As String = "C:\Users\Admin\Documents\test.csv"
Dim OutlookLines As New List(Of OutlookLine)
Dim sr As New IO.StreamReader(FILE_NAME)
Do Until sr.EndOfStream
OutlookLines.Add(New OutlookLine With {.line = sr.ReadLine})
Loop
DataGridView1.DataSource = OutlookLines
End Sub
Private Class OutlookLine
Private theLine As String
Public Property line() As String
Get
Return theLine
End Get
Set(ByVal value As String)
theLine = value
End Set
End Property
End Class
End Class
我嘗試輸入:
.Split(","c)
在sr.ReadLine之后,但顯示“無法將String的類型1-D數組的值轉換為String”
上面的代碼工作正常,但csv的每一行都被壓縮為一列(顯然是因為我沒有將其拆分為“,”)。
CSV數據:
1,2,3,4,5
6,7,8,9,0
看看這是否適合您:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.DataSource = CSVToDataTable("C:\Users\Admin\Documents\test.csv", True)
End Sub
Private Function CSVToDataTable(filePath As String, Optional hasHeaderRow As Boolean = False) As DataTable
Dim rows = IO.File.ReadAllLines(filePath).Select(Function(l) l.Split(","c))
Dim dt = New DataTable
Dim count = 0
dt.Columns.AddRange(rows.First.Select(Function(c) New DataColumn With {.ColumnName = If(hasHeaderRow, c, "Column" & Threading.Interlocked.Increment(count))}).ToArray())
For Each row In rows.Skip(If(hasHeaderRow, 1, 0))
Dim dr = dt.NewRow()
dr.ItemArray = row
dt.Rows.Add(dr)
Next
Return dt
End Function
如果希望OutlookLine類的line屬性是字符串數組,則應按以下方式定義它:
Private Class OutlookLine
Private theLine As String()
Public Property line As String()
Get
Return theLine
End Get
Set(ByVal value As String())
theLine = value
End Set
End Property
End Class
然后這將起作用:
OutlookLines.Add(New OutlookLine With {.line = sr.ReadLine.Split(",")})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.