Home All Groups Group Topic Archive Search About

Creating a CSV from query results

Author
22 Mar 2006 12:19 AM
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

Author
22 Mar 2006 1:24 AM
Steven Nagy
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()
Author
22 Mar 2006 1:39 AM
Michelle
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
Author
22 Mar 2006 1:46 AM
Al Reid
"Michelle" <nospam_mbytwo-news@yahoo.com.au> wrote in message
news:dvq9rk$gja$1@otis.netspace.net.au...
> 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.

--
Al Reid
Author
22 Mar 2006 3:07 AM
Michelle
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*
Author
22 Mar 2006 5:56 AM
Cor Ligthert [MVP]
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