views:

39

answers:

2

One of my users wants to get data into Excel from SQL 2008 query/stored proc.

I never actually did it before.

I tried a sample using ADO and got data but user reasonably asked - where are the column names?

How do I connect a spreadsheet to an SQL resultset and get it with column names?

A: 

Apparently the field names are in the recordset object already.. just needed to pull them out.

i = 1
For Each objField In rs.Fields
    Sheet1.Cells(1, i) = objField.Name
    i = i + 1
Next objField
Bobb
A: 

I don't know which version of Excel you are using but in Excel 2007 you can just connect to the SQL DB by going to Data -> From Other Sources -> From SQL Server. After you select your server and database, your connection will be created. Then you can edit it (Data -> Connections -> Properties) where in the Definition tab you change the Command type to SQL and enter your query in the Command text box. You can also create a view on the server and just point to that from Excel.

This should do it unless I misunderstood your question.

kaloyan
I use 2003.. However - in your answer on 2007 - will you get column names with the resultset from SQL?? thats the question (not how to get data - thats simple, but how to get it with column names - see bold font in the question).. Cheers
Bobb
you would get the column names, yes.
kaloyan
thank you. will keep in mind if we move to 2007.
Bobb
I bet this feature is in 2003 as well -- I just don't have it in front of me to tell you what the exact interface steps are. I am sure that if you click around you will find it, though. There is a benefit in using the built-in Excel features and not VBA.
kaloyan