Export data from SQL Server to Excel

By:   |   Updated: 2016-02-01   |   Comments (36)   |   Related: 1 | 2 | 3 | 4 | 5 | > Microsoft Excel Integration


Problem

Exporting data from SQL Server to Excel seems like a reasonably simple request. I just need to write out a few reports for users on a regular basis, nothing too fancy, the same basic report with a few different parameters. What native SQL Server options are available to do so? Do I need to learn another tool or can I use some T-SQL commands? Does SQL Server 2005 offer any new options to enhance this process?

Solution

Exporting data from SQL Server to Excel can be achieved in a variety of ways. Some of these options include Data Transformation Services (DTS), SQL Server Integration Services (SSIS) and Bulk Copy (BCP). Data Transformation Services (SQL Server 2000) and SQL Server Integration Services (SQL Server 2005) offers a GUI where widgets can be dragged and dropped Each option has advantages and disadvantages, but all can do the job. It is just a matter of your comfort level with the tools and the best solution to meet the need.

Another option that is available directly via the T-SQL language is the OPENROWSET command (SQL Server 2000 and SQL Server 2005). This command can be called directly in any stored procedure, script or SQL Server Job from T-SQL. Below outlines the full syntax available:

OPENROWSET 
( { 'provider_name' , { 'datasource' ; 'user_id' ; 'password' 
   | 'provider_string' } 
      , {   [ catalog. ] [ schema. ] object 
       | 'query' 
     } 
   | BULK 'data_file' , 
       { FORMATFILE = 'format_file_path' [  ]
       | SINGLE_BLOB | SINGLE_CLOB | SINGLE_NCLOB }
} ) 
 ::=
   [ , CODEPAGE = { 'ACP' | 'OEM' | 'RAW' | 'code_page' } ] 
   [ , ERRORFILE = 'file_name' ]
   [ , FIRSTROW = first_row ] 
   [ , LASTROW = last_row ] 
   [ , MAXERRORS = maximum_errors ] 
   [ , ROWS_PER_BATCH = rows_per_batch ] 

Source - SQL Server 2005 Books Online

Below is a simple example of writing out the Job name and date to Sheet1 of an Excel spreadsheet in either SQL Server 2005 or 2000:

INSERT INTO OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=C:\testing.xls;', 
'SELECT Name, Date FROM [Sheet1$]') 
SELECT [Name], GETDATE() FROM msdb.dbo.sysjobs
GO

Using the OPENROWSET command creates two caveats. The first caveat is the need to have an Excel spreadsheet serve as a template in the needed directory with the correct worksheets and columns. Without this the you would receive an error message. The second caveat is that it is necessary to enable the OPENROWSET command with the SQL Server 2005 Surface Area Configuration utility. Note - This step is not needed for SQL Server 2000. With the loop example you could copy and paste the Excel spreadsheet and load the data as needed.

Although the example above is very simple, you could integrate this simple example into your code. For example, if you had the need to write out a number of reports in the same format, you could loop (WHILE loop or Cursor) over the records and write them out to different Excel spreadsheets based on the name or report type. In addition, you could integrate this code with either SQL Server 2000 mail or Database mail (SQL Server 2005) and mail the results to the users with very little effort and build the process entirely with T-SQL.

Next Steps


sql server categories

sql server webinars

subscribe to mssqltips

sql server tutorials

sql server white papers

next tip



About the author
MSSQLTips author Jeremy Kadlec Jeremy Kadlec is a Co-Founder, Editor and Author at MSSQLTips.com with more than 300 contributions. He is also the CTO @ Edgewood Solutions and a six-time SQL Server MVP. Jeremy brings 20+ years of SQL Server DBA and Developer experience to the community after earning a bachelor's degree from SSU and master's from UMBC.

This author pledges the content of this article is based on professional experience and not AI generated.

View all my tips


Article Last Updated: 2016-02-01

Comments For This Article




Wednesday, July 5, 2017 - 10:34:28 AM - Dick Rosenberg Back To Top (58914)

 I have all my tables in my data base and can loop through them with a cursor based on  'SELECT * FROM INFORMATION_SCHEMA.TABLES. I have my template.xslx.

I would like to either

 

1 - Have a different Excel File name for each file (Including a date stamp)

2 - Have a Different tab for each table that I am writing ouot (with the name of the tab being the name of the table

Starting with the exmaple posted below, how would I accomplish either (or am I stuck with having my output spreadsheet be c:\texting.xlsx. And if I am stuck with having my output spreadsheet be c:/testing.xlsx can I clean it out (equivalent of TRUNCATE TABLE) for the next time I run it. The number of tables that I have to make into a spreadsheet(s) will vary from run to run. It depends on how many clients have bad data.

 

Thanks,

Dick

 

INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=C:\testing.xlsx;Extended Properties="Excel 12.0 Xml;HDR=NO";', 

'SELECT Name, Date FROM [Sheet1$]') 

SELECT [Name], GETDATE() FROM msdb.dbo.sysjobs

 

 

 

 


Friday, June 30, 2017 - 3:31:56 AM - Peter Back To Top (58590)

 SQL Server 2005 in 2016? Really? However, the example can easely adapted to newer OLEDB versions (Microsoft.ACE.OLEDB.12.0').

Somthing like this:

INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=C:\testing.xlsx;Extended Properties="Excel 12.0 Xml;HDR=NO";', 

'SELECT Name, Date FROM [Sheet1$]') 

SELECT [Name], GETDATE() FROM msdb.dbo.sysjobs

 Make sure the security settings allow 'Ad Hoc Distributed Queries'

 


Friday, June 30, 2017 - 2:02:05 AM - Christian Back To Top (58588)

On MS-SQL-Server 2016 I use R in-database to export to Excel. This is very easy when R-services are setup once. Just use TSQL and pass any table as input to an "exec sp_executeexternalscript" and let R do the job (e.g. with package foreign).

With older versions I prefer to export to csv formating everything within TSQL in a way the superintelligence of excel would eat it. Unfortunately Excel behaves different depending on language of OS and other settings within excel. So my best advice for "How to export to Excel": If possible - don't. Using import function from excel is one way to do so.

 

Best regards

Christian


Wednesday, November 30, 2016 - 12:34:17 PM - Afan Back To Top (44867)

 

 Sir i have only one question would it possible that i am insert something on Excel sheet & its simultaneously insert the same thing on myadmin php sql..

 

 

Thanks 


Friday, November 18, 2016 - 10:35:51 AM - Russell R Thompson Back To Top (43803)

 I sympothise ... I would expect an easy export function built into SSMS similar to MS Access.   To that point, I use MS Access regularly linked to Sql Server just for this functionality.   You select a query in MS Access (which is linked to a Sql Server) .. and simply click an Export to Excel button and "presto" all your results With Headers are now in MS Excel.

 


Friday, May 6, 2016 - 10:44:05 AM - Jeremy Kadlec Back To Top (41420)

Rx_,

I would probably look at SQL Server Reporting Services and/or PowerBI.  Here are a few points of reference:

https://www.mssqltips.com/sqlservertutorial/222/sql-server-reporting-services-ssrs-tutorial/

https://www.mssqltips.com/sqlservertip/3527/export-sql-server-reporting-services-report-data-into-multiple-excel-worksheets/

https://www.mssqltips.com/sql-server-tip-category/211/power-bi/

https://www.mssqltips.com/sql-server-business-intelligence-resources/

 

HTH.

Thank you,
Jeremy Kadlec
Community Co-Leader

 

 

 


Friday, May 6, 2016 - 7:57:53 AM - Rx_ Back To Top (41416)

 As an Excel Object Model Programmer able to connect with SQL Server Native Client to SQL Server, clients expect highly complex and custom Excel worksheets with formatting, filters,  formulas included and also custom Excel formatting based on business rules.

Running Excel code with linked tables from MSAccess or MSExcel is one way to accomplish this.

How can the Excel Object Model VBA equalivant code be run from TSQL.

A view or table exported to Excel is not useful to the client. They want to see complex Excel "reports" automated from nightly batch or triggers.

Are there any tools in MSSQL to help generate more than just  a table or view simple export?

 


Wednesday, September 2, 2015 - 12:28:42 PM - Tim Back To Top (38587)

The code from the tip is this which references a sql agent job:

SELECT [Name], GETDATE() FROM msdb.dbo.sysjobs

How do I have to setup the sql agent job?

 


Tuesday, May 12, 2015 - 8:31:52 AM - Leif Back To Top (37155)

You can also use MS-Query to import data from SQL server and then REFRESH data in Excel when needed.

You can have very complex queries with multiple outer joins in MS-Query provided You write the code as "derived table" :

--------------

Example:

select * from

( complex query )    AS A

----------------------------------------------------

 

 


Sunday, January 4, 2015 - 7:43:21 AM - Ali Back To Top (35817)

Error:

 

Cannot get the column information from OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "(null)".


Wednesday, November 26, 2014 - 2:49:16 AM - Ram Back To Top (35409)

INSERT INTO OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=C:\testing.xls;', 'SELECT Name, Date FROM [Sheet1$]') 

SELECT EMP_NM, DOB FROM mt_emp_hdr

GO

when I am executing the above code, I am getting following error. 

Msg 7399, Level 16, State 1, Line 1

The OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "(null)" reported an error. The provider did not give any information about the error.

Msg 7303, Level 16, State 1, Line 1

Cannot initialize the data source object of OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "(null)".

 

Kinldy respond.

Ram


Thursday, May 22, 2014 - 1:20:20 AM - ponraman Back To Top (30880)

INSERT INTO OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=D:\pon.xls;', 
'SELECT Name, Date FROM [Sheet1$]') 
SELECT PtMt_Name FROM Lb_PtMt_Patient_Mast_T

GO


when i run this above query it is showing error like "The OLE DB provider "Microsoft.Jet.OLEDB.4.0" has not been registered."

but it is working sql server 2005 but not working in sql server 2008 r2 .  i want to export data from sql server to excel in sql server 2008 r2


Thursday, July 11, 2013 - 12:11:12 PM - Jeremy Kadlec Back To Top (25801)

Lynore,

Check out this tip -http://www.mssqltips.com/sqlservertip/2676/export-data-to-an-earlier-sql-server-version/.

HTH.

Thank you,
Jeremy Kadlec
Community Co-Leader

 


Wednesday, July 10, 2013 - 11:54:07 AM - Lynore Back To Top (25779)

hi i need some help with exporting a table from my database (sql server R2 2008) to another database also using sql server R2 2008.

 

 


Tuesday, June 26, 2012 - 4:23:00 PM - Edward Jd Back To Top (18205)

Using current tools in Ms Excel (Data\From Other Sources\From SQL Server or Data\From Other Sources\From MS Query) almost give the same result, except that SQL data can be filtered before being exported inito Excel speadsheet. The export process is quite easy & there's no any issue when the number of record is not over than 65536.


Thursday, March 22, 2012 - 12:56:52 AM - JIT Back To Top (16574)

Eagerly waiting for answer............


Tuesday, March 20, 2012 - 6:53:54 AM - JIT Back To Top (16529)

How to export data into Formatted Excel Sheet Using OPENROWSET From SQL Server

Formatted Sheet Means it has table which starts from 5th row of excel sheet


Tuesday, February 21, 2012 - 2:51:57 AM - f Back To Top (16108)

Go the Data ribbon in Excel 2007, click on "From Other Sources" in the "Get External Data" area on the left side.  It will ask you for the login credentials to your database.  Data is dumped right into Excel, with automatic row formatting, and all those miserable blank cells you might get with a straight html copy/paste are automatically removed.  Easy peasy!


Wednesday, December 9, 2009 - 11:29:47 AM - Lisa7 Back To Top (4532)

How to export MSSQL data to Excel 2007:

OMG, I am posting this to save others hours of frustration importing MSSQL data into Excel.  I'm with Rothy who posted earlier (THANK YOU!).  Use Excel's data import function to do this, it is so much easier than messing around with MSSQL query code. It took me ONE MINUTE to import an MSSQL table and most of that time was spent looking up my login credentials;)

Go the Data ribbon in Excel 2007, click on "From Other Sources" in the "Get External Data" area on the left side.  It will ask you for the login credentials to your database.  Data is dumped right into Excel, with automatic row formatting, and all those miserable blank cells you might get with a straight html copy/paste are automatically removed.  Easy peasy! 


Tuesday, June 23, 2009 - 6:22:26 PM - ssivaprasad Back To Top (3627)

I am getting error below, while trying to export the query data into a excel file

Msg 8152, Level 16, State 4, Line 2
String or binary data would be truncated.
The statement has been terminated.


Tuesday, April 21, 2009 - 3:18:22 PM - Rothy Back To Top (3224)

 Go to Skype.com and download the latest version. I assumed that most people would have Skype but if you don't know what it is then it may not be a good option. If you want to phone me instead thenlet me know with a private message.

 To change the name of a tab you merely double click on it and type the new name.  As the spreadsheet can be saved and reused repeately this once-off operation probably doesn't warrant a macro.

 To send the macro to someone else, edit the macro then cut-and-paste the text into an emai. The co-worker can then paste it into a new macro. Probably just easier to send the spreadsheet with the macro to the co-worker.

 


Tuesday, April 21, 2009 - 11:13:31 AM - hoodmayor Back To Top (3220)

I was playing around with creating a Macro this morning and have one saved in my 'All open Workbooks'.

How can I copy the saved Macro and send it to a co-worker for testing on his PC?

I am not sure if this is the path I should take or did you want to show me something else from my comments yesterday?

btw ....how do we hook up with Skype?

Thank you for your support!

Joe 

 


Monday, April 20, 2009 - 2:10:59 PM - hoodmayor Back To Top (3209)

Thanks.

I will see what I can create today with each select for each table, but I am not sure how I can save the sheet with the table name.

if you have time to hook-up tomorrow, that would be real helpful.

Thanks,  Joe

 


Monday, April 20, 2009 - 1:07:04 PM - Rothy Back To Top (3207)

 Yes - using the method described; from Excel, select each table you require rather than the SysTableView. You can rename the sheet-tab with the name of the table.

If you are still having trouble we can hook-up through Skype.

 


Monday, April 20, 2009 - 10:12:38 AM - hoodmayor Back To Top (3206)

following the steps all I got was the tables names listed in cell a of the excel file.

I was looking to create a sheet in the excel file for each of the sql tables (with all columns & rows) populated into the sheet and the sheet having the same name as the table.

Can this be done using this method?

Thanks!


Monday, April 20, 2009 - 9:08:06 AM - hoodmayor Back To Top (3205)

Thanks I will try this now.


Friday, April 17, 2009 - 5:46:16 PM - Rothy Back To Top (3195)

 First create a query with the commands that grobido has provided. Call it SysTableView or whatever is appropriate.

Then in an Excel sheet do the following..

\Data
Import External Data
New Database Query

Switch off the query wizard

Create a new data source pointing to your MS SQL database.

Select the query above "SysTableView"

Select the relevent fields

 From the Records dropdown menu switch off automatic query

 From the File menu select "Return Data to Microsoft Office Excel"

 Select OK

 ...from now on all you have to do is refresh the query within Excell to get the latest information.

 

 


Friday, April 17, 2009 - 10:36:36 AM - hoodmayor Back To Top (3194)

I  just need to find the best way to copy my domain tables from a MSSQL 2005 db into an excel file, with each tables as a sheet (with same format & all rows).

I was trying to use the openrowset, but can't seem to get the format  correct?

Do you have any ideas for an easy way to do this with t-sql script?

Thanks.

Joe 

 


Friday, April 17, 2009 - 9:39:40 AM - hoodmayor Back To Top (3193)

Thank you so much!

I I just need to find the best way to copy these tables into an excel file, with each tables as a sheet (with same format & all rows).

I was trying to use the openrowset, but can't seem to get the format  correct?

Do you have any ideas for an easy way to do this with t-sql script?

Thanks.

Joe 

 


Friday, April 17, 2009 - 9:04:32 AM - grobido Back To Top (3192)

SELECT name
FROM sys.sysobjects
WHERE name like '%[_]d'
AND xtype = 'U'


Friday, April 17, 2009 - 9:01:05 AM - hoodmayor Back To Top (3191)

How would I omit the views & pk_ , & fk_ from the list, so I only have the table names that end with '_d'?


Friday, April 17, 2009 - 5:22:02 AM - grobido Back To Top (3187)

This assumes you are in the database you want to use.

SELECT name
FROM sys.sysobjects
WHERE name like '%[_]d'


Thursday, April 16, 2009 - 3:20:51 PM - hoodmayor Back To Top (3184)

I am looking for the best way to select table names that end with '_d' from a sql 2005 db and create a worksheet with the table name into one excel 2003 file.

Leaving the the format the same and with all rows from the tables where is_pickable is true.

Can you provide me with a sample T-sql script to do this?

Thanks.

Joe 

 


Sunday, April 5, 2009 - 11:35:02 PM - sridar.be Back To Top (3137)

While Executing the following Query i got the output as follows
and the excel file was not created in selected path
Please help me
Query:
EXEC master..xp_cmdshell 'BCP "select * from iplan_polaris.DBO.IP_PERSON Where LEN(PE_LOGN) = 5" queryout Contacts.txt -c -T '

Output:
NULL
Starting copy...
NULL
951 rows copied.
Network packet size (bytes): 4096
Clock Time (ms.): total       31
NULL


My Questin:
1. While excuting the above qry, the Excel file was not created in selected path... What can i do now?
2. Excel file was created automatically i.e.created by sql server or created by manually?
3. any other alternative option is there in sql server 2005?

Its urgent
Please help me as soon as possible
thanks in advance
Sri


Thursday, April 2, 2009 - 2:03:02 AM - Rothy Back To Top (3116)

My answer is DON'T. Rather let Excel suck it in from the database.

The simplest solution I would suggest is to use the Databse Query facility within Excel. I use this extensively and you can pass parameters through to filter data.

It uses MS Query to pull the info from any ODBC linked database and feeds it directly into Excel with a simple refresh inside Excel. 

The best part is that you can format all your reports once in Excel and you never have to do it again.

If you give your users read-only access to the database they can refresh the data themselves. And they can make modifications to the Excel report on their own too.

The data can be fed into either a flat table or a pivot table in Excel.

All you need to do is provide the data in a query in your database and let Excel pull it in from the query.

I use this so much I rarely even bother writing reports in the database.

 

 

 


Tuesday, December 9, 2008 - 12:02:04 AM - Patrickdh Back To Top (2369)

Hi ,

   How do i install "'Microsoft.Jet.OLEDB.4.0'" driver on a 64bit sql server 2005 server ?















get free sql tips
agree to terms