How to Parse a CSV File Using VB
The format CSV (comma separated values) is one of the most common for data files. A comma is used to delineate objects on each line of the file. Many applications, such as Excel, output data in this format. Programmers will load the data from a csv file into a code structure such as an array or table. Visual Basic 2008 provides features reducing the code required to parse (separate a large block of data into distinct items) a csv file.
Instructions
-
-
1
We will create and parse a simple data file for purposes of illustration. Open the text editor and enter the following data:
1,2,3,4,5,6
A,B,C,D,E -
2
Save this file to "c:\test.csv".
-
-
3
Open the Visual Basic application and create a new project using the "Ctrl" and "N" keys. Select the "Windows Forms Application" template.
-
4
Create a button labeled "Button1" on the form.
-
5
Double click on "Button1" and enter the following code:
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser _
("c:\test.csv")
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
'set the delimiter to any value
MyReader.Delimiters = New String() {","}Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
'ouput the second value of each line to show that the file has been parsed.
MsgBox(currentRow(1))
' Include code here to handle the row.
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
" is invalid. Skipping")
End TryEnd While
End Using
-
6
Execute the code in debug mode using the "F5" key.
-
7
Click on "Button1" to executed the parsing code. A message box for each line in the file will appear on the screen with the second value of that line displayed.
-
1
Tips & Warnings
Altering the delimiter value in the code will allow this code to be used for multiple file types.