Creating a CSV from query results

  • Thread starter Thread starter Michelle
  • Start date Start date
M

Michelle

Hi

I'm trying to create a .csv file from a list of records that are returned
from a query.

Any links / code samples / help is appreciated

Michelle
 
ADO supports reading/writing from Excel just like it does to any other
database.
So you have the option of specifying that Excel is the datasource
(check MSDN).

Or you can write a simple loop to iterate through all your rows / cols
to write the contents out with a streamwriter.
Something like this (note: this is untested code) which is based on a
comma delimiter::

Dim sw as new StreamWriter("test.csv", false)
Dim outstring as string = ""
for each dr as datarow in myDatatable.Rows
dim first as boolean = true
for each dc as datacolumn in myDatatable.Columns
if first then
outstring &= dr(dc.ColumnName)
else
outstring &= ", " & dr(dc.ColumnName)
end if
next
outstring &= VbCrLf
next
sw.Write(outstring)
sw.Close()
 
Thanks Steven

I will have a look at your post in further detail over the next couple of
days (understand that it's untested).

I just need a start to learn how to read from a query set that I produce in
either SQL Express or Access.

Michelle
 
Michelle said:
Thanks Steven

I will have a look at your post in further detail over the next couple of
days (understand that it's untested).

I just need a start to learn how to read from a query set that I produce
in either SQL Express or Access.

Michelle

One additional note. If the data you are retrieving has embedded commas in
them (i.e. City, State zip) the example will not produce a correct CSV file.
At a minimum, strings should be enclosed in quotes, just to be safe.
 
Good tip Al. Thanks for that.

In most cases, each field *should* not have any commas, but of course, as
developers we know how often things shouldn't happen, yet they do. *grin*
 
Michelle,

And than as extra tip. See what is the CSV "comma" seperator in your local
culture. If you are setting it yourself. AFAIK is outside the English
languages cultures the delimiter a ";"

I hope this helps,

Cor
 
Back
Top