How to Create a CVS File in VB.Net
Submitted by janobe on Tuesday, January 29, 2019 - 20:55.
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.
For any questions about this article. You can contact me @
Email – [email protected]
Mobile No. – 09305235027 – TNT
Or feel free to comment below.
Creating Application
Step 1
Open Microsoft Visual Studio 2015 and create a new windows form application in visual basic.Step 2
Add a Button into the form.Step 3
Create a method to read and write a CSV file using StreamWriter and StreamReader.- Public Sub WriteCSVfile()
- Try
- '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
- File.Delete("c:\CSV\TestingOut.csv")
- 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)
- strList.Add(strvalues(0))
- 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
- stReader.Close()
- 'It will write a string to the stream
- stWriter.Write(str)
- 'It will close the current object and the underlying stream
- stWriter.Close()
- Catch ex As Exception
- 'Catching errors
- MessageBox.Show(ex.Message)
- End Try
- End Sub
Step 4
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
- WriteCSVfile()
- End Sub
Comments
Add new comment
- Add new comment
- 5795 views