将CSV文件读入多个数组

时间:2016-03-02 23:53:39

标签: arrays vb.net

如果我想从CSV文件中将以下内容读入4个独立的数组,我将如何处理?
例如:

John,Doe,100,98
Jane,Smith,90,90

我需要带一个学生的第一个&姓。一年级是他们的中期,第二年是他们的决赛。

    Dim Name As String = ""
    Dim inFile As StreamReader
    Dim outFile As StreamWriter

    inFile = File.OpenText("grades.csv")
    outFile = File.CreateText("report.txt")


    Do While (Not inFile.EndOfStream)
        Name = CStr(inFile.ReadToEnd)
        outFile.WriteLine(Name)
    Loop

    inFile.Close()
    outFile.Close()

我看到了百万种不同的分割方式,我只输出文件以查看我得到的内容。有人可以帮助我将这些分成不同的数组吗?感谢

1 个答案:

答案 0 :(得分:0)

试试这个.....这个例子可能会给你一些想法......

Imports System.Data.OleDb

Public Class Form1

Private dt As New DataTable

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim folder = "<Path to the folder of your grades.csv file (don't include the file name, just the path up to the folder)>"
    Dim CnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & folder & ";Extended Properties=""text;HDR=No;FMT=Delimited"";"
    ' in the next line replace grades.csv with the name of your file....
    Using Adp As New OleDbDataAdapter("select F1 + ' ' + F2 as FirstSecondName, F3 as MidTerm, F4 as Final from [grades.csv] ", CnStr)
        Try
            Adp.Fill(dt)
        Catch ex As Exception

        End Try
    End Using
    Me.ListBox1.DataSource = dt
    ListBox1.DisplayMember = "FirstSecondName"
    ListBox1.ValueMember = "FirstSecondName"

    AddHandler ListBox1.SelectedIndexChanged, AddressOf ListBox1_SelectedIndexChanged
End Sub

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
    Dim senderListBox As ListBox = sender
    If senderListBox.SelectedIndex <> -1 Then
        Dim SelectedData As DataRowView = senderListBox.SelectedItem
        MessageBox.Show(String.Format("Selected - {0} :: Mid-Term Result = {1} :: Final Result = {2}", SelectedData("FirstSecondName").ToString, SelectedData("MidTerm").ToString, SelectedData("Final").ToString))
    End If
End Sub

End Class