但是,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
答案 0 :(得分:1)
看看这是否适合你:
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
答案 1 :(得分:0)
如果您希望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(",")})