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.

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application in visual basic. ps1

Step 2

Add a Button into the form. ps2

Step 3

Create a method to read and write a CSV file using StreamWriter and StreamReader.
  1. Public Sub WriteCSVfile()
  2. Try
  3. 'A TextReader is use to read character from a byte in a particular encoding
  4. Dim stReader As StreamReader = New System.IO.StreamReader(File.OpenRead("c:\CSV\Testing.csv"))
  5.  
  6. 'It initialize the instance of List(of String) class that has the default initial capacity
  7. Dim strList As New List(Of String)()
  8.  
  9. 'It validates whether the particular file is already exist
  10. If File.Exists("c:\CSV\TestingOut.csv") Then
  11. 'Deleting the file
  12. File.Delete("c:\CSV\TestingOut.csv")
  13. End If
  14.  
  15. 'For the specified file, you have to initialize a new instance of the StreamWriter class
  16. 'for encoding and buffering the size
  17. Dim stWriter As New StreamWriter("c:\CSV\TestingOut.csv")
  18. 'Declare an empty string variable
  19. Dim str As String = String.Empty
  20.  
  21. While stReader.Peek() >= 0
  22. Dim strline As String = stReader.ReadLine()
  23. Dim strvalues As String() = strline.Split(";"c)
  24. strList.Add(strvalues(0))
  25. str = str + strline + Chr(10)
  26. End While
  27.  
  28. 'It will close the StreamReader object and the underlying stream
  29. 'It releases any system resources associate the reader
  30. stReader.Close()
  31. 'It will write a string to the stream
  32. stWriter.Write(str)
  33. 'It will close the current object and the underlying stream
  34. stWriter.Close()
  35.  
  36. Catch ex As Exception
  37. 'Catching errors
  38. MessageBox.Show(ex.Message)
  39. End Try
  40.  
  41. 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.
  1. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  2. WriteCSVfile()
  3. 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.

Comments

Submitted byWalt S. (not verified)on Thu, 09/26/2019 - 08:05

Works great! But, what is the 'List' object for? It doesn't seem to do anything. Thanks.

Add new comment