How to Create a CVS File in VB.Net
Let’s learn how to create CSV file in Visual Basic 2015. CSV file is a Comma Separated Value that is a commonly used format in text editor such as Microsoft Excel, OpenOffice Calc, notepad and Google docs. It is a plain text file that contains a list of data record. Each of its data record consist one or more fields that are separated by commas. So, in this tutorial, I’m going to teach you how to read and write the CSV file in a simple way. Just follow the steps below to see how it works.
Open Microsoft Visual Studio 2015 and create a new windows form application in visual basic.
Add a Button into the form.
Create a method to read and write a CSV file using StreamWriter and StreamReader.
- Public Sub WriteCSVfile()
- 'A TextReader is use to read character from a byte in a particular encoding
- Dim stReader As StreamReader = New System.IO.StreamReader(File.OpenRead("c:\CSV\Testing.csv"))
- 'It initialize the instance of List(of String) class that has the default initial capacity
- Dim strList As New List(Of String)()
- 'It validates whether the particular file is already exist
- If File.Exists("c:\CSV\TestingOut.csv") Then
- 'Deleting the file
- End If
- 'For the specified file, you have to initialize a new instance of the StreamWriter class
- 'for encoding and buffering the size
- Dim stWriter As New StreamWriter("c:\CSV\TestingOut.csv")
- 'Declare an empty string variable
- Dim str As String = String.Empty
- While stReader.Peek() >= 0
- Dim strline As String = stReader.ReadLine()
- Dim strvalues As String() = strline.Split(";"c)
- str = str + strline + Chr(10)
- End While
- 'It will close the StreamReader object and the underlying stream
- 'It releases any system resources associate the reader
- 'It will write a string to the stream
- 'It will close the current object and the underlying stream
- Catch ex As Exception
- 'Catching errors
- End Try
- End Sub
Double click a button to fire the
click event handler of it and do the following codes for reading and writing CSV file in the specified path when the button is clicked.
- Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
- End Sub
For any questions about this article. You can contact me @
Email – [email protected]
Mobile No. – 09305235027 – TNT
Or feel free to comment below.