• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2618
  • Last Modified:

VB.Net - Output SQL Query Results to CSV File

Good Day Experts!

I have little project here that seems pretty straightforward.  I need to query a SQL Server database and get a resultset(not sure whether I am going to use a DataReader or DataTable).
When I loop through the results, I need to write each record to a CSV file.  

I have not done this before so I have searched the net and found differing iterations.
Do you have any recommended reference sites that I could check out?

2 Solutions
You can write some methods that would do this. Here's a quick and dirty one, haven't tested it. Takes a DataTable as input, and outputs CSV with the column names as headers.

Private Function GetCSVFromTable(table As DataTable) As String
	Dim csvString = New StringBuilder()
	For i As Integer = 0 To table.Columns.Count - 1
		csvString.Append(If(table.Columns.Count - 1 Is i, vbLf, ","))
	For Each row As var In table.AsEnumerable()
		For i As Integer = 0 To table.Columns.Count - 1
			csvString.Append(If(table.Columns.Count - 1 Is i, vbLf, ","))
	Return csvString.ToString()
End Function

Open in new window

Jimbo99999Author Commented:
Excellent information. I have it working now!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now