How to Parse a CSV File in VB
CSV is a acronym for Comma Separated Values. Files of this type are unformatted text files that contain tables of data normally separated by commas, but they could also be tab delimited or have fixed-width fields of text. CSV files are normally associated with the .csv file-name extension. In programming, the process of reading data from these files is called parsing.
Instructions
-
Parse a CSV File in VB
-
1
Create a new object in your program, the code for an object called MyParser would read:
Using MyParser As New
-
2
Call on the VB TextFieldParser Object and give the file path to the text or .cvs file you want to parse. The code would change to suit the file path and name of your document.
Microsoft.VisualBasic.FileIO.TextFieldParser _(\"C:\\MyFolder\\MyDoc.csv\")
-
-
3
Set the file structure to delimited. This needs to be done as the TextFieldParser is also capable of parsing fixed width text files. The code for comma delimited parsing would read:
MyParser.TextFieldType = FileIO.FieldType.Delimited
-
4
Set the delimiter type. For comma separated values the delimited is a comma. The code would read:
MyReader.SetDelimiters(",")
-
5
State that the data being read is text based: "As String." The code would read:
Dim MyParserRow As String()
-
6
Call upon the ReadFeilds method to read or parse the data. The code would read:
currentRow = MyParser.ReadFields()
The text from the first row of the CSV has been read, and split into fields by the ReadFields method and can now be manipulated as needed.
-
1
References
Resources
- Photo Credit ANSI image by DBX60 from Fotolia.com