T-SQL: Export Table to Excel

What you do to export data from SQL to excel. You use data import/export wizard or just simply execute the select query and copy the whole lot of data in an excel file with headers. Copy and paste the data in the excel sheet is the quickest possible solution I can see…but what if you have to data through your code? Still there are many possible ways to accomplish this but how many lines of code you have to write to achieve this? maybe most of the people definately have a simple and reliable way. Ok…lets do this using T-SQL query. The only problem I see here is that you must have a excel file in the location defined in the query before you execute the query.

In one of our application we maintain log in a sql table for all the tasks done in the whole day. The administrator of the application want to take a look at all the tasks done by a particular user, he didn’t want any UI to look into this instead he asks us to generate a report at the end of the day in excel on a button click. So lets see the code.

Execute the below query to set the configuration of SQL Server to 1. In my case there was no change as I already executed this query in the past. But, most probably you will see a change in the your case the value could be changed from 0 to 1.

EXEC sp_configure 'show advanced options', 1;
GO RECONFIGURE;
GO EXEC sp_configure 'Ad Hoc Distributed Queries', 1;
GO RECONFIGURE;
GO

After you set the configuration option execute a normal select query to get all the column names and paste them in the excel sheet. Then save the excel sheet in your local hard drive.

Select TOP 0 * From Person.Address
 
--For Office 2003 (.XLS) format
INSERT INTO OPENROWSET ('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=c:\contact.xls;','SELECT * FROM [Sheet1$]')SELECT * FROM authors
 
--For Office 2007 (.XLSX) format
INSERT INTO OPENROWSET ('Microsoft.ACE.OLEDB.12.0', 'Excel 8.0;Database=c:\contact.xlsx;','SELECT * FROM [Sheet1$]')SELECT * FROM authors
comments powered by Disqus