Exporting data from sql server to excel

There are several ways to Export/Import SQL Server data to an Excel file. In this article, a couple of ways to import and export SQL Server data to an Excel file will be explained:

  • Export SQL Server data to an Excel file using
    • the SQL Server Import and Export Wizard
    • T-SQL code
    • Export to Excel from ApexSQL Complete
  • Import SQL Server data into Excel using the Data Connection Wizard

In SQL Server Management Studio (SSMS), there is a feature that provides for exporting data from one data source to another data source; in this case, data from SQL Server will be copied to an Excel file trough Export Wizard.

To start to use this feature, go to Object Explorer, right click on any database (e.g. AdventureworksDW2016CTP3), under the Tasks, choose Export Data command:

This will open the SQL Server Import and Export Wizard window:

To proceed with exporting SQL Server data to an Excel file, click the Next button. This will open the Choose a Data Source window. On this window, a source from which you want to copy data can be chosen:

From the Data source drop down box, choose the SQL Server Native Client 11.0 item. Under the Server name drop down box, choose the SQL Server instance from which data need to be copied. In the Authentication section, choose the authentication mode for the data source connection and under the Database drop down box, choose the database from which the data will be copied. After all these options are set, click the Next button to proceed.

This will open the Choose a Destination window in which can be specified where to copy data from the data source:

In the Destination drop down box, choose the Microsoft Excel item. Under the Excel file path, choose the destination for copied data from SQL Server data source (SQL Data.xlsx). In the Excel version drop down box, choose the version of the Microsoft Excel worksheet. After these are all set, press the Next button to continue. But after pressing the Next button, the following warning message may appear:

The operation could not be completed.
ADDITIONAL INFORMATION:
The ‘Microsoft.ACE.OLEDB.12.0’ provider is not registered on the local machine. (System.Data)

This happens because SSMS is a 32-bit application and when you launch the Export Wizard via SSMS, it launches a 32-bit version of Export Wizard. On the other hand, the machine (Operating system) on which SSMS is installed is a 64-bit version and the installed SQL Server is a 64-bit version.

To solve this problem, close SSMS, go to the Start menu and find the 64-bit version of SQL Server Import and Export Data:

After launching this SQL Server Import and Export Wizard, it will be prompted with the same window that is used via SSMS. After setting all previous options, click the Next button. The Specify Table Copy or Query window will appear:

On this window, whether to copy data from one or more tables and views or to copy the results of a query can be specified.

Select the Copy data from one or more tables or views radio button and click the Next button. The Select Source Table and Views window allows choosing one or more tables and views from which you want to export SQL Server data to an Excel file by clicking the check box next to the name of the table/view:

As it may be noticed, as soon as the check box next to a table/view is checked, the name of the table/view will be copied under the Destination column. This name represents the name of the sheet where the data from the table will be put, this name can be changed to whatever you like, but for now, it will be left as it is:

To preview which data will be generated to an Excel file, click the Preview button:

After choosing which tables/views data will be copied to an Excel file, click the Next button:

On the Save as Run Package window, check the Run immediately check box and click the Next button:

The Complete the Wizard window shows all options that are chosen for exporting operations. To finalize the process of export SQL Server data to an Excel file, click the Finish button. The last SQL Server Import and Export Wizard window shows the state of the data have been successfully exported or some errors occurred during exporting data:

In our case, the data were successfully generated into the SQL Data.xlsx file in the DimScenario sheet:

Export SQL Server data to an Excel file using T-SQL code

The Transact-SQL OPENROWSET can be used to export SQL Server data to an Excel file via SSMS. In a query editor type and execute the following code:

INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;
Database=C:UsersZivkoDesktopSQL Data.xlsx;'
,'SELECT * FROM [Sheet1$]')
SELECT * FROM dbo.DimScenario

But, when executing the above code, the following error may occur:

Msg 15281, Level 16, State 1, Line 1
SQL Server blocked access to STATEMENT ‘OpenRowset/OpenDatasource’ of component ‘Ad Hoc Distributed Queries’ because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of ‘Ad Hoc Distributed Queries’ by using sp_configure. For more information about enabling ‘Ad Hoc Distributed Queries’, search for ‘Ad Hoc Distributed Queries’ in SQL Server Books Online.

To resolve this error the Ad Hoc Distributed Queries option should be enabled This can be done by using the sp_configure procedure and executing the following SQL code in a query editor:

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

After executing the above code, the following message will appear that indicate that the show advanced options and Ad Hoc Distributed Queries options are enabled:

Configuration option ‘show advanced options’ changed from 0 to 1. Run the RECONFIGURE statement to install.
Configuration option ‘Ad Hoc Distributed Queries’ changed from 0 to 1. Run the RECONFIGURE statement to install.

Now, when again the code is executed:

INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;
Database=C:UsersZivkoDesktopSQL Data.xlsx;'
,'SELECT * FROM [Sheet1$]')
SELECT * FROM dbo.DimScenario

The following error may appear:

OLE DB provider “Microsoft.ACE.OLEDB.12.0” for linked server “(null)” returned message “The Microsoft Access database engine cannot open or write to the file ”. It is already opened exclusively by another user, or you need permission to view and write its data.”.
Msg 7303, Level 16, State 1, Line 1
Cannot initialize the data source object of OLE DB provider “Microsoft.ACE.OLEDB.12.0” for linked server “(null)

This usually happens because of inadequate permissions.

More about how to resolving these issues can be found in the How to query Excel data using SQL Server linked servers page.

One way for resolving this issue is to open SSMS as an administrator and execute the code again. But this time, another error may appear:

Msg 213, Level 16, State 1, Line 1
Column name or number of supplied values does not match table definition.

To resolved this, open excel file (e.g. SQL Data.xlsx) for which is planned to store the data from SQL Server table (e.g. dbo.DimScenario) and enter the column names which will represent the column names from the DimScenario table:

Close the SQL Data.xlsx file and once again execute the code:

Now, the following message will appear:

(3 rows affected)

Finally, the data from the SQL Server table are copied into the Excel file:

Import SQL Server data into Excel using the Data Connection Wizard dialog

Another way to copy data from SQL Server table to an Excel file is to use the Data Connection Wizard dialog from Excel.

In order to achieve that, open an Excel file (e.g. SQL Data.xlsx) in which you want to import data. In the Data tab, under the From Other Source sub-menu, choose the From SQL Server command:

This will open the Data Connection Wizard dialog. In the Server name, enter a name of the SQL Server instance from which data need to be copied. In the Log on credentials section, choose the authentication mode for the data source connection and click the Next button:

From the Select the database that contains the data you want drop down box, choose the database from which the data will be copied. In the grid, all available tables and views will be listed. Choose a desired table / view (e.g. DimScenario) and click the Next button to proceed.

On this window, leave everything as it is and press the Finish button:

In the Import Data dialog, choose the Table radio button, under the Where do you want to put the data? section, choose the Existing worksheet radio button and press the OK button:

After pressing the OK button, the data from the DimScenario table will be copied to the SQL Data.xslx file:

Export SQL Server data to an Excel file using Export to Excel from ApexSQL Complete

Using the Export to Excel feature from ApexSQL Complete, add-in for SSMS and Visual Studio, exporting data from the SQL Server table to an Excel file can be done by one click.

In a query editor, type and execute the following code:

SELECT * FROM dbo.DimScenario ds

From the Results grid, select data that you want to export to an Excel file, right click in the Result grid and, from the context menu, choose the Export to Excel option:

This will open a new Excel workbook and the selected data from the Results grid will be copied in the first worksheet:

More about exporting to Excel via ApexSQL Complete can be found on the Export to Excel page.

See also:

  • Tutorial: Import Data into Excel, and Create a Data Model
  • Get started with this simple example of the Import and Export Wizard
  • How to query Excel data using SQL Server linked servers
  • Export to Excel

September 11, 2017

Export table from SQL Server to Excel

In a previous article, SQL and Excel: Why you need both, we showed that for many businesses the use of both SQL Server and Excel is an optimum approach to data management.  For organizations that use SQL Server and Excel extensively, there is often a need to export data from SQL Server to Excel.  The most common reasons to get the data into Excel are to:

  • produce data visualizations such as charts and graphs for use in reports
  • aggregate or analyze data in pivot charts
  • collate data from multiple sources for further transformation
  • make the data available to non-database users to view or process

In this article, we’re going to look at how to export data from SQL Server to Excel.  The first method uses the SQL Server Import and Export Wizard, which can be used to export data to a number of destination types, not just Excel.  The second method uses native functionality in Excel.  The third method uses the SQL Spreads Add-In for Excel, which provides functionality beyond the export process.  There are pros and cons of each method, which we’ll summarise at the end of the article.

Table of contents

  • 1. Method (1): Exporting using SQL Server Import and Export Wizard
  • 2. Method (2): Exporting using native functionality in Excel
  • 3. Method (3): Exporting using SQL Spreads Add-In for Excel
  • 4. Summary

Method (1): Exporting using SQL Server Import and Export Wizard

The SQL Server Import and Export Wizard can be launched from within SQL Server Management Studio or as a stand-alone application.

From within SQL Server Management Studio, click on the database from which you want to export data.  We’re using the demo database in our example, so click on that and then right-click and select Tasks > Export Data.

ssms_launch_export_wizard

The Welcome page is displayed, and you can go ahead and click ‘Next’.

wizard_welcome

On the next screen, select the data source.  To export from SQL Server, select ‘SQL Server Native Client’.

wizard_select_data_source

Once you’ve selected ‘SQL Server Native Client’, the details about the data source will be populated by the wizard.

Click ‘Next’ to go to the next screen, where you going to choose the destination for the export, which for us is Excel.

wizard_select_data_destination_excel

When you select Excel as the choice of destination, you then need to provide the location of the Excel file.  When you then click ‘Next’, you may see the following message:

The operation could not be completed.
ADDITIONAL INFORMATION:
The ‘Microsoft.ACE.OLEDB.16.0’ provider is not registered on the local machine. (System.Data)

wizard_warning

The reason this message appears is that when you launch the SQL Server Import and Export Wizard from SSMS, a 32-bit version of the wizard is launched (because SSMS is 32-bit) and your operating system is 64-bit.  There is more information on this here.

To get around this, you need to close SSMS and go to the Windows Start menu and search for the 64-bit version of the SQL Server Import and Export Wizard from the Start menu.  Note that this version will only be installed on your computer if you have installed SQL Server.

wizard_launch_from_start

Once the stand-alone version of the Wizard has started, you can go through the steps as discussed so far, which was to specify the source and destination of the data copy.  We now need to define what we want to copy, and (optionally) configure the copy operation.

After clicking ‘Next’ on the ‘Choose a Destination’ screen, you specify whether you want to export one or more complete tables or views, or a subset of data via a SQL query.  In our case, we are exporting from a single table, so we can leave the default option selected.

Next, we’re going to edit the column mappings by clicking the ‘Edit Mappings…’ button.  The Column Mappings screen allows you to make changes to the name and data type of the columns that will be created in Excel by the copy operation.  In our example, we’re going to change the data type for the ‘order_date’ column from VarChar to DateTime.  We’ll leave the others as the default set by the wizard. Click ‘Next’.  The next screen in the wizard summarizes that the source is a SQL table called sales and the destination will be to a sheet called ‘sales’ in the Excel workbook.  You can change the name of the sheet as needed.

Once done, click ‘Ok’ to close the dialog and then ‘Next’.

If any of the mappings that we specified may not succeed in the export process the SQL Server Import and Export Wizard shows the Review Data Type Mapping page. This page will highlight the conversions that the wizard needs to perform to handle the mappings that you have specified. It also indicates what the wizard will do if a there is an error during the conversion.  It can either ignore the error or cause the export to fail.  In our example, several columns have been flagged: the ones where there is a conversion from nvarchar(max) to its Excel equivalent, Long Text, and also  the conversion from VarChar to DateTime for the ‘order_date’ column.  The default setting is for the wizard to fail if there is an error, so we’ll leave that option in place.

wizard_review_data_mapping

Note: This SQL Import and Export Wizard uses SSIS under the hood; in other words, each time you run the wizard, you are creating an SSIS package.  This is why you are given the option of saving it for future use.Click ‘Next’.  The wizard now offers you the chance to save the Wizard configuration as an SSIS package in addition to the default option of running the copy immediately.

We are just going to leave the default option ticked and then click the ‘Next’ button.

The wizard now displays a summary of the steps that we have configured.

wizard_complete_the_wizard

Click ‘Finish’, and the wizard will now show the final screen, which is the result of the execution.  In our case, the execution was successful, and we can see that 5484 records were copied to the ‘Query’ sheet in our Excel workbook.

wizard_execution_successful

We can check that the data has been exported from SQL Server to Excel by opening up the file that we specified and checking the ‘sales’ sheet.

sales_data_in_excel

Now that the data is in Excel, we can create some visualizations or aggregations, or whatever other processing we want to perform.  For example, we could create a pivot chart to display the Total per item per region.

Method (2): Exporting using native functionality in Excel

Although the method itself is much the same, Microsoft has made improvements in the last few releases to the way you get data from other sources into Excel.  The main change was the addition of the Power Query data import wizards and tools as a native component in Excel 2016.  These are accessed from the Power Query Editor, although it’s not displayed as such on the Excel Ribbon – instead, it is branded as Get & Transform Data group on the Data tab of the Excel ribbon.

excel_get_and_transform_data

The steps described below are valid for Excel 2016 and beyond.

To get started with the export from SQL Server to Excel, click on Data > Get Data > From Database > From SQL Server Database.

excel_getdata_fromsql

You are next prompted to enter the database server to connect to and, optionally, specify a database.  If you don’t specify a database, you can select from the available ones on the next screen.

excel_specify_server

Click ‘Ok’. You’ll then be prompted to provide authentication details.  The default is Windows, so you can go ahead and click ‘Connect’.

excel_database_authentication

The next screen allows you to navigate through the databases and tables on the database server that you specified.  Click on the ‘demo’ database to expand it and then click on the ‘sales’ table.  The data for the selected table is displayed in the right-hand window.  We could now click the ‘Load’ button to get the data into Excel immediately.  Alternatively, we can click on ‘Transform Data’ to perform transformations on the data (eg change data types, clean up some data, perform computations).  For this example, we’re just going to load the data as it is, so go ahead and click ‘Load’.

excel_navigate_to_db

The data is now exported from the table in SQL Server and loaded into a new sheet in Excel.

That is all we need to do to perform a simple export of a full table from SQL Server to Excel. Aside from the simple procedure we’ve described here, the Power Query data import wizards and tools provide ways to ‘shape’ the data from external sources.  For example, you can remove a column, change a data type, merge tables to meet your specific needs.

Method (3): Exporting using SQL Spreads Add-In for Excel

If you don’t already have the SQL Spreads Add-In for Excel installed, you can download a copy here.

Once SQL Spreads is installed, you’ll see that it has been added as a new ribbon tab; go here and click the Design Mode button.

sqlspreads_click_design_mode

In the SQL Spreads Designer panel on the right side, click the Edit button to open the SQL Server connection dialog.

sqlspreads_editconnection

Enter the name of your SQL Server into the SQL Server name field.  You also need to choose an authentication method: Windows-login (Windows Authentication) or SQL Server Authentication (using a name and password set up in SQL Server).  Windows authentication is the more secure of the two options.

sqlspreads_connection_details

Click OK. SQL Spreads will try to connect to the database. If the connection is successful, your databases will show up in the SQL Spreads Designer panel.

sqlspreads_designer_db_list

We can now expand the demo database and select the sales table.

When you click on the table, the data is immediately exported from SQL Server and copied to a sheet called ‘sales’ in Excel.

sqlspreads_sales_data_in_excel

That’s it!  We’ve managed to export data from SQL Server to Excel with just a couple of clicks.

There are several more options available to us in the SQL Spreads Designer.  For example, we can:

  • filter the data that is exported from SQL Server
  • set whether certain columns are displayed and/or read-only
  • use a look-up value to display text instead of an id for a column
  • sort data
  • make updates in Excel and save changes to SQL Server

There is more information on these features in the SQL Spreads knowledgebase here.

Summary

Being able to export data from SQL Server to Excel is a common requirement in most businesses.  We’ve looked at three methods for performing this day-to-day task.  The first uses the SQL Server Import and Export Wizard, which is native functionality in SQL Server.  The second method uses the native ‘Get & Transform’ tools in Excel.  The third uses the SQL Spreads Add-In for Excel.

So which method should you use?

If you normally work with databases, and SSMS is your second home, you’ll probably feel that the SQL Server Import and Export Wizard is the best option for you.  If you are an Excel user, then it makes sense to work from within Excel itself to export data from SQL Server.  Both of the two Excel options that we’ve looked at are robust and easy to use, but SQL Spreads has a distinct advantage because it allows users to make updates to data directly in Excel and then save the data back to SQL Server.  This is a huge advantage for those organizations that like the best of both worlds: the ease of use and familiarity of Excel, with the power and data integrity associated with SQL Server.

Try SQL Spreads to see how quick and easy it is to export data from SQL Server to Excel; download a free trial version today.

*This article was originally published on August 26, 2021 and was updated on July 4, 2022 to include some new screenshots.

Andy

Andy McDonald

Andy has worked 20+ years in the Engineering, Financial, and IT sectors with data analysis and presentation using tools such as SQL Server, Excel, Power Query and Power BI.

Writes for SQL Spreads about Excel and SQL Server and how to tie those two together.

«Hello, I am new to SQL. We use SQL query in SQL 2016 Server. And then we are exporting the output to excel. Could you please guide me on how to make the process automated for exporting data from SQL to Excel. Since I don’t want to do the task manually any longer. «

If you come across the same problem as mentioned above and want to find a way to export SQL Server data to Excel, don’t fret. This page covers two possible ways to help you export data from SQL Server automatically.

Two Ways to Export Data from SQL Server to Excel

You can use the SQL Server Import and Export Wizard and Data Connection Wizard in Excel to export data from SQL Server to Excel. See the details below. 

Solution 1. Use the SQL Server Import and Export Wizard

1. Open SQL Server Management Studio and connect to the database. 

2. Go to «Object Explorer», find the server database you want to export to Excel. Right-click on it and choose «Tasks» > «Export Data» to export table data in SQL. Then, the SQL Server Import and Export Wizard welcome window pop up. 

export data from SQL Server to Excel - 2

3. Now, you need to click on the Data source drop-down button to choose the data source you want to copy. Here, select «SQL Server Native Client 11.0». In the Server name drop-down box, select a SQL Server instance. In the Authentication section, choose authentication for the data source connection and from the Database drop-down box, select a database from which data will be copied. After everything is set, press the «Next» button. 

export data from SQL Server to Excel - 3

4. On the «Choose a Destination» window, in the Destination box, choose Microsoft Excel item for exporting data from SQL Server to Excel. Choose the Excel file path and version as you need. Then, click the «Next» button to continue.

export data from SQL Server to Excel - 4

5. On the Specify Table Copy or Query screen, you can choose «Copy data from one or more tables or views». Then, click «Next» to go on.

export data from SQL Server to Excel - 5

6. In the «Select Source Table and Views» window, you can choose one or more tables and views from which you want to export SQL Server data to an Excel. Click the «Preview» button to preview which data will be generated to an Excel file. Click the «Next» button to move on. 

export data from SQL Server to Excel - 6

7. Here, on the «Save and Run Package» window, check the «Run immediately» and click the «Next» button.

export data from SQL Server to Excel - 7

8. On the «Complete» Wizard window, you can check all the settings set during of exporting process. If everything is right, click «Finish» to start exporting SQL database to Excel.

export data from SQL Server to Excel - 8

9. You can view the exporting process in this step. When it completes, click on «Report» drop-down button.

export data from SQL Server to Excel - 9

10. You can choose «Save Report to File…» (including Excel, Notepad) to save the report. Here, you need to choose Excel as the target file format. 

export data from SQL Server to Excel - 10

How to Repair SQL Server Database

SQL Server Management Studio (SSMS) offers the Import and Export Wizard feature to export data from one data source to another data source. Namely, you can apply this function to export SQL to Excel. For exporting SQL Server database to CSV, link to check the details.

Step 1. Close the SQL Service in Task Manager or SQL Server Manager Console.

Step 2. Run EaseUS MS SQL Recovery, click «Browse» (the two dots) or «Search» to choose the location where you saved your corrupted database. Afterward, Click «Repair» to start analyzing the specified database.

select the SQL database file

Step 3. When it has done, choose the files you want to repair and click «Export».

Select the database objects

Step 4. Turn on the SQL service, you can choose to export the repaired files to database to export it as SQL scripts.

export the SQL database objects

Solution 2. Using the Data Connection Wizard in Excel

Another way to export data from SQL Server to Excel file is to use the Data Connection Wizard dialog in Excel.

1. Launch Excel, open an Excel file in which you want to export SQL Server data. On the toolbar, click the «Data» tab > select «From Other Sources» > choose «From SQL Server».

export SQL data to Excel - 1

2. The «Data Connection Wizard» window will pop up. Enter the name of the SQL Server instance from which data need to export. In the «Log on credentials» section, choose «Use Windows Authentication» mode for the data source connection and click the «Next» button.

export SQL data to Excel - 2

3. Choose the database from which the data will be exported. And click the «Next» button to proceed. On the next window, leave everything as it is and press the «Finish» button.

export SQL data to Excel - 3

4. In the Import Data dialog, choose «Table» and «Existing worksheet» as the screenshot shows. Press the «OK» button. After this, the SQL Server data will be exported to Excel file. 

export SQL data to Excel - 4

In several scenarios, we need to use some data which is available in SQL Server, but we need it in MS Excel. Instead of putting every data manually into Excel, the SQL Server provides an option to import and export data from SQL Server to Excel sheets. In this tutorial, we will learn various methods of importing and exporting data from or to SQL Server. Also, we will cover these topics.

  • How to export data from SQL Server to Excel using Import and Export Wizard
  • How to export data from SQL Server to Excel automatically
  • How to export data from SQL Server to Excel using the query
  • How to import data from SQL Server into Excel using Data Connection Wizard
  • Export data from SQL Server to Excel using stored procedures

Here, for all the functionality, I have used SQL Server 2019 Express edition.

Export data from SQL Server to Excel using Import and Export Wizard

In this section, we will learn how to export data from the SQL Server database into an Excel worksheet automatically using import & export Wizard. We will be using the import and export wizard in SQL Server Management Studio.

  • Below is the table that we are going to export automatically using the import and export wizard in SQL Server.
export data from SQL Server to Excel using Import and Export Wizard
Data to be Imported
  • Right-click on the database using which table is created.
  • Select the Tasks option from the dropdown another dropdown will appear.
  • Click on the Export Data.
Import to Excel Wizard in sql server
Running the Import and Export Wizard
  • Once you have clicked on the Export Data option from the drop-down menu then Import and Export wizard window will appear.
  • Click on Next to proceed in the process.
Export data from SQL Server to Excel
Import and Export Wizard
  • Once you have clicked on the Next button on Import and Export wizard a new window will appear asking to Choose a Data Source
  • Select SQL Server Native Client 11.0 in Data Source
  • Select the instance from the dropdown for the Server name.
  • For Authentication, you can use:
    • Use Windows Authentication, which means the username and password of your computer. It automatically picks up from the system.
    • Use SQL Server Authentication, this requests the Username and Password that was creating an instance.
  • Select the database name from the dropdown and click on the Next button.
export data from SQL Server to Excel using Import and Export Wizard
Data Source
  • The SQL Server Import and Export Wizard will ask for destination details. Choose Destination field as Microsoft Excel
  • Give the path to the Excel file into which you want to export the data
  • Select the Excel Version according to the version of the Excel that you have installed on your system and click Next.
How to export data from SQL Server to Excel using Import and Export Wizard
Data Destination
  • Now the SQL Server Import and Export Wizard will ask whether you want to copy all data from the existing tables or query-specific data. We can select Copy data from one or more tables or views to import all the table data.
  • We will also explain how you can copy data that is modified by SQL query with Write a query to specify the data to transfer option

Read: How to Create a Database in SQL Server 2019 [Step by Step]

Export data from SQL Server to Excel automatically

SQL Server 2019 provides a method to export all the data from SQL server to Excel worksheet. In this section, we will demonstrate how to export SQL server data to Excel automatically using Import and Export Wizard.

Import to SQL specify table copy
Specify type of Operation
  • Choose the table from the Source tab which you want to export and specify the name of the table in the Destination tab and click Next
How to export data from SQL Server to Excel
Select Table
  • In the next step, you can choose whether you want to save the SSIS Package or not. In this section, we will continue without saving.
How to export data from SQL Server 2019 to Excel
Run Package
  • Now you will see the final overview of the operation before the execution, click on the Finish Button.
How to export data from SQL Server to Excel automatically
Final Overview
  • Now data has been successfully exported from SQL Server to Excel worksheet.Click on the Close button to exit the window.
How to export data from SQL Server to Excel
Process Completed
  • You can check that the file is created at the specified location.
How to export data from SQL Server to Excel automatically
Exported Data Successfully

Read: How to create a table in sql server management studio

At times, it is not necessary to export all the table data. Instead, we need to export data using a query. In such situations, we can export query-specific data from SQL Server to Excel worksheet.

  • After selecting the source and destination of data using SQL Import and Export Wizard, the wizard show two options. Choose the second option which says Write a query to specify the data to transfer and then click on the Next button.
export data from SQL Server to Excel using query
Export Using Query
  • Then we need to specify the query which we want to implement. In our case we will execute a query to show the Name and Age of people whose salaries are greater than 100000. After writing the query, click Next
export data from SQL Server 2019 to Excel using query
Writing the Query
  • Now you will see the overview of table source and destination. You can also see how the data looks after the query is implemented by clicking on the Preview button. Then click Next
export data from SQL Server 2017 to Excel using query
Data Preview
  • Run immediately is checked by default, click on Next button.
How to export data from SQL Server to Excel using query
Save and Run Package Windows
  • Now all the configurations are complete. You can click on the Finish button to start the Wizard
How to export data from SQL Server to Excel using query
Complete the Wizard
  • If all actions are successfully completed, your query is implemented and the data is exported. You can close this window.
Import from SQL to Excel Execution success
Success
  • Navigate to the destination path and you can see that data is exported successfully
How to export data from SQL Server to Excel using query
Exported Data

Read: Advanced Stored Procedure Examples in SQL Server

How to import data from SQL Server into Excel using Data Connection Wizard

We can also import data from SQL Server to Excel using the Data Connection Wizard in Excel. The benefit of using this method is that we can get live data from SQL Server.

Live data means that the changes made in the SQL Server database will be reflected into the Excel worksheet also. We will demonstrate this with the help of an example

  • Open MS Excel and create a new worksheet or open an existing worksheet into which you want to import the data from SQL Server
  • Go to the Data tab and click on From Other Sources and then From SQL Server as shown in the image below
import data from SQL Server into Excel
Create Connection to SQL Server
  • Enter the name of the Server instance that you have created in the Server name field. You can use either Windows Authentication or SQL Server login credentials to make a connection with the database. After inserting the required details, click Next
import data from SQL Server 2019 into Excel
Data Connection Wizard
  • Now select the database and the table that you want to import. You can also import data from multiple tables by checking the option Enable selection of multiple tables
How to import data from SQL Server into Excel
Select Database and Table
  • Save the Data Connection File. Add description to it to store more information about the connection. It will help you to know the information about the connection when you will connect to the database again. Click Next
How to import data from SQL Server 2019 into Excel
Save Connection
  • A small window will appear where you can decide how you want to view your data in the Excel Workbook. You can import the data either in an existing worksheet or in a new worksheet. Select the desired option and then click OK
How to import data from SQL Server 2017 into Excel
Format Data
  • Now you can see, your data is imported successfully from SQL Server
How to import data from SQL Server into Excel
Imported Data
  • As mentioned above, this type of connection is a live connection to the database. Try to change the data in SQL Server. You will see that the changes will be reflected in the Excel worksheet also. Let us see an example
  • Run the following query in the SQL Query Window in SQL Studio Management
update Employees set Age =20 where [Employee ID]=1;
select * from Employees;

Here is the implementation of above mentioned code snippet.

import to excel updated data studio
Result after Query
  • Changes are made in the table. Now refresh the excel worksheet where you have imported the data or open it again. You will the same changes in the imported data
how to import data from SQL Server into MS Excel
Updated Data

In this tutorial, we have learned how to import data from SQL Server into MS Excel using Import and Export wizard in different ways. Also, we have covered these topics.

Export data from SQL Server to Excel using stored procedures

  • There is a method in SQL Server called OPENROWSET method which is used to export data from SQL Server to Excel
  • OPENROWSET method has some requirements that need to be fulfilled before we can use this method
    • Administrator permissions to SQL Server Management Studio
    • enable “Show Advanced Options”
    • enable “Ad Hoc Distributed Queries”
  • Run SQL Server Management Studio as Administrator
  • Write the query following query to enable these options
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
EXEC sp_configure 'Ad Hoc Distributed Queries',1;
RECONFIGURE;
GO
Export data from SQL Server to Excel
Configuring sp_configure
  • Give permissions to the Microsoft.ACE.OLEDB.12.0 driver by excecuting the following command
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
  • After successfully running the above commands, you have to create an Excel sheet with the same fields which are there in the database table
Export data from SQL Server 2019 to Excel
Field Names
  • Now you can write the query to export data from SQL Server to Excel
INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;
Database=C:UsersBladesDesktopexported_data.xls;','SELECT * FROM [Sheet1$]')
Select * from Employees;
  • Remember to set the Database path, Excel file name, Excel worksheet name and database name in the above query
  • You may encounter the following error while executing the query
  • This error states that the SQL Server is running on 64-bit architecture but Microsoft Access Database Engine only has 32-bit drivers installed

How to Export data from SQL Server to Excel

Version Error

This means you have to download the 64-bit Access Database Engine

You can download the 64-bit version of Access Database Engine from the specified link

Install Access Database Engine and this will install the 64-bit version of Microsoft.ACE.OLEDB.12.0 driver.

Now run the query again

INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;
Database=C:UsersBladesDesktopexported_data.xls;','SELECT * FROM [Sheet1$]')
Select * from Employees;
  • Now you can see, the query is run successfully
Export data from SQL Server 2019 to Excel using stored procedures
Success Message
  • You can open the Excel file and see if the data is exported
Export data from SQL Server to Excel using stored procedures
Exported Data
  • You can use this OPENROWSET method in your own stored procedure and export data from SQL Server to Excel.

You may like the following sql server articles:

  • SQL Server Substring Function
  • SQL Server Replace Function + Examples
  • SQL Server Convert String to Date

In this tutorial, we learned about the various methods of exporting the data from SQL Server to Excel. We solved some encountered errors also.

  • How to export data from SQL Server to Excel using Import and Export Wizard
  • How to export data from SQL Server to Excel automatically
  • How to export data from SQL Server to Excel using the query
  • How to import data from SQL Server into Excel using Data Connection Wizard
  • Export data from SQL Server to Excel using stored procedures

Bijay

I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.

Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.

For anyone coming here looking for how to do this in C#, I have tried the following method and had success in dotnet core 2.0.3 and entity framework core 2.0.3

First create your model class.

public class User
{  
    public string Name { get; set; }  
    public int Address { get; set; }  
    public int ZIP { get; set; }  
    public string Gender { get; set; }  
} 

Then install EPPlus Nuget package. (I used version 4.0.5, probably will work for other versions as well.)

Install-Package EPPlus -Version 4.0.5

The create ExcelExportHelper class, which will contain the logic to convert dataset to Excel rows. This class do not have dependencies with your model class or dataset.

public class ExcelExportHelper
    {
        public static string ExcelContentType
        {
            get
            { return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; }
        }

        public static DataTable ListToDataTable<T>(List<T> data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable dataTable = new DataTable();

            for (int i = 0; i < properties.Count; i++)
            {
                PropertyDescriptor property = properties[i];
                dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
            }

            object[] values = new object[properties.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = properties[i].GetValue(item);
                }

                dataTable.Rows.Add(values);
            }
            return dataTable;
        }

        public static byte[] ExportExcel(DataTable dataTable, string heading = "", bool showSrNo = false, params string[] columnsToTake)
        {

            byte[] result = null;
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(String.Format("{0} Data", heading));
                int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3;

                if (showSrNo)
                {
                    DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));
                    dataColumn.SetOrdinal(0);
                    int index = 1;
                    foreach (DataRow item in dataTable.Rows)
                    {
                        item[0] = index;
                        index++;
                    }
                }


                // add the content into the Excel file  
                workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);

                // autofit width of cells with small content  
                int columnIndex = 1;
                foreach (DataColumn column in dataTable.Columns)
                {
                    int maxLength;
                    ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];
                    try
                    {
                        maxLength = columnCells.Max(cell => cell.Value.ToString().Count());
                    }
                    catch (Exception) //nishanc
                    {
                        maxLength = columnCells.Max(cell => (cell.Value +"").ToString().Length);
                    }

                    //workSheet.Column(columnIndex).AutoFit();
                    if (maxLength < 150)
                    {
                        //workSheet.Column(columnIndex).AutoFit();
                    }


                    columnIndex++;
                }

                // format header - bold, yellow on black  
                using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count])
                {
                    r.Style.Font.Color.SetColor(System.Drawing.Color.White);
                    r.Style.Font.Bold = true;
                    r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    r.Style.Fill.BackgroundColor.SetColor(Color.Brown);
                }

                // format cells - add borders  
                using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
                {
                    r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Right.Style = ExcelBorderStyle.Thin;

                    r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
                }

                // removed ignored columns  
                for (int i = dataTable.Columns.Count - 1; i >= 0; i--)
                {
                    if (i == 0 && showSrNo)
                    {
                        continue;
                    }
                    if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName))
                    {
                        workSheet.DeleteColumn(i + 1);
                    }
                }

                if (!String.IsNullOrEmpty(heading))
                {
                    workSheet.Cells["A1"].Value = heading;
                   // workSheet.Cells["A1"].Style.Font.Size = 20;

                    workSheet.InsertColumn(1, 1);
                    workSheet.InsertRow(1, 1);
                    workSheet.Column(1).Width = 10;
                }

                result = package.GetAsByteArray();
            }

            return result;
        }

        public static byte[] ExportExcel<T>(List<T> data, string Heading = "", bool showSlno = false, params string[] ColumnsToTake)
        {
            return ExportExcel(ListToDataTable<T>(data), Heading, showSlno, ColumnsToTake);
        }
    }

Now add this method where you want to generate the excel file, probably for a method in the controller. You can pass parameters for your stored procedure as well. Note that the return type of the method is FileContentResult. Whatever query you execute, important thing is you must have the results in a List.

[HttpPost]
public async Task<FileContentResult> Create([Bind("Id,StartDate,EndDate")] GetReport getReport)
{
    DateTime startDate = getReport.StartDate;
    DateTime endDate = getReport.EndDate;

    // call the stored procedure and store dataset in a List.
    List<User> users = _context.Reports.FromSql("exec dbo.SP_GetEmpReport @start={0}, @end={1}", startDate, endDate).ToList();
    //set custome column names
    string[] columns = { "Name", "Address", "ZIP", "Gender"};
    byte[] filecontent = ExcelExportHelper.ExportExcel(users, "Users", true, columns);
    // set file name.
    return File(filecontent, ExcelExportHelper.ExcelContentType, "Report.xlsx"); 
}

More details can be found here

Like this post? Please share to your friends:
  • Export vba from excel
  • Export to word from html
  • Export to excel yii2
  • Export to excel with php
  • Export to excel sas