Comma Separated Value (CSV) format is a common format used to exchange data between different programs that may not support each other's native format. For example, it can be used to exchange spreadsheet data between Excel and another spreadsheet, or database data between Access and MySQL. Visual Basic does not contain an automatic function for loading CSV files, however one of the reasons for its widespread support is its simplicity. As the name implies, CSV files are nothing but a list of values, each separated by a comma or a new line. It is fairly simple to create a CSV reader in Visual Basic.
- Skill level:
Other People Are Reading
Create a new project by clicking "File" and "New Project."
Drag a button onto your form from the toolbox using your mouse.
Find the "OpenFileDialog" control and add it to your form as well. Since this control is initially invisible, it will not appear on your form, but rather beneath it.
Double-click on the button to create an event that will occur whenever the user clicks the button. Paste the following code that will ask the user for a CSV file and load its data into a 2D array:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 	 	REM Get the file the user wants to load. OpenFileDialog1.ShowDialog() Dim filename As String = OpenFileDialog1.FileName Dim file Stream As System.IO.StreamReader = New System.IO.StreamReader(filename)
REM Read all the data from the file into a single string. Dim contents As String = fileStream.ReadToEnd
REM Split the string into its values. After this operation is finished, there will be a one dimensional array of values, and the end of the rows will be marked by empty strings. Dim values = contents.Split() Dim arr As ArrayList = New ArrayList Dim rows As ArrayList = New ArrayList
REM Move the data into a 2D array. For x As Integer = 0 To lines.Length - 1 If lines(x) IsNot String.Empty Then arr.Add(lines(x)) End If rows.Add(arr.Clone) arr.Clear() Next
Dim data(rows.Count, rows(0).count) As String For x As Integer = 0 To rows.Count - 1 For y As Integer = 0 To rows(x).count - 1 data(x, y) = rows(x)(y) Next Next End Sub
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for