How to Export Data from SQL Server to Excel Table in C#
Tags: csharp, dotnet, productivity, sql
Published: 2019-09-12 12:31:38

---
title: How to Export Data from SQL Server to Excel Table in C#
published: true
tags: csharp, dotnet, productivity, sql
canonical_url: https://www.syncfusion.com/blogs/post/export-data-from-sql-server-to-excel-in-c-sharp.aspx
cover_image: https://www.syncfusion.com/blogs/wp-content/uploads/2019/07/Thumbnail_1x.jpg
---
[Microsoft Excel](https://en.wikipedia.org/wiki/Microsoft_Excel) is known for storing, analyzing, and visualizing data. [Databases](https://en.wikipedia.org/wiki/Database) are great for storing a large set of data. At times, you may need to use or analyze data from a database in Excel.

In this article, we are going to see how the [Syncfusion .NET Excel (XlsIO) library](https://www.syncfusion.com/excel-framework/net) helps you export data from [SQL Server](https://en.wikipedia.org/wiki/Microsoft_SQL_Server) to Excel in C# through external data connections, export filtered data using query parameters, and programmatically refresh Excel data when its database is updated.

Before we see how to export data from SQL Server to Excel, you must understand Excel tables, because Microsoft Excel allows data to be exported from SQL Server to Excel tables. Excel tables allow you to analyze data quickly and easily by performing operations such as sorting, filtering, calculating, and formatting.

## **How to export data from SQL Server to Excel**

In this blog, we are going to use an  **Employee\_Details**  table from a database mapped to an Excel table. We have used the following query to fill an Excel table from a database:

```sql
select * from Employee_Details;
```

![Data Exported from SQL Server to Excel](https://www.syncfusion.com/blogs/wp-content/uploads/2019/08/Excel-table-with-external-connection.png)

<figcaption>Data Exported from SQL Server to Excel</figcaption>

Let’s see the steps involved in exporting data from SQL Server to Excel using C#. Before proceeding with the following steps, refer to the [Getting Started guide](https://help.syncfusion.com/file-formats/xlsio/getting-started) for the assemblies required to create an Excel file.

**Step 1:** Create the instances of  **_ExcelEngine_** and  **_IApplication_**. It is like opening an Excel application.

**Step 2:** Create a new workbook instance with one worksheet.

**Step 3:** Create a connection string to establish a connection with a SQL Server database and query string to retrieve data from a SQL Server database similar to ADO.NET.

**Step 4:** Establish the connection to the workbook with the connection string and query string.

**Step 5:**  Create an Excel table with an external data connection using the AddEx method of the **_IWorksheet.ListObjects_ ** collection class.

**Step 6:** Pull the data from the database and store it in Excel using the **_Refresh()_** method of the **_IListObject_ ** class.

**Step 7:** Save the Excel file and close its instances.

The following code sample shows how to export data from a database to an Excel table.

```csharp
private void btnCreateExcel_Click(object sender, EventArgs e)
{
    using (ExcelEngine excelEngine = new ExcelEngine())
    {
        IApplication application = excelEngine.Excel;
        application.DefaultVersion = ExcelVersion.Excel2016;
 
        //Create a new workbook 
        IWorkbook workbook = application.Workbooks.Create(1);
        IWorksheet sheet = workbook.Worksheets[0];
 
        if (sheet.ListObjects.Count == 0)
        {
            //Estabilishing the connection in the worksheet 
            string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password = myPassword";
 
            string query = "SELECT * FROM Employees";
 
            IConnection connection = workbook.Connections.Add("SQLConnection", "Sample connection with SQL Server", connectionString, query, ExcelCommandType.Sql);
 
            //Create Excel table from external connection. 
            sheet.ListObjects.AddEx(ExcelListObjectSourceType.SrcQuery, connection, sheet.Range["A1"]);
        }
 
        //Refresh Excel table to get updated values from database 
        sheet.ListObjects[0].Refresh();
 
        sheet.UsedRange.AutofitColumns();
 
        //Save the file in the given path 
        Stream excelStream = File.Create(Path.GetFullPath(@"Output.xlsx"));
 
        workbook.SaveAs(excelStream);
        excelStream.Dispose();
    }
}
```

## **How to export data using query parameters in an Excel table**

To export data from SQL Server to an Excel table, queries are used. Queries always return the same results, and their data cannot be filtered at runtime. Therefore, Microsoft Excel provides the option  **Parameter** , which is used to get dynamic values, apply them to the query, and return filtered results. Parameters can be set either through a prompt event, as a constant, or as an Excel range. Developers can write a query and leave it up to the end-user to filter data on their own. The values entered as parameters are used in the **WHERE** clause of the SQL query. The available parameter types are:

- Prompt parameter
- Constant parameter
- Range parameter

Let’s see these parameter types in detail and how to implement them.

### Prompt parameter

The prompt parameter type helps the user by raising a prompt event where a filter value can be entered at runtime on refreshing the Excel table. This is useful when there is a need to filter the Excel table with different values.

The following code example illustrates how to set two parameters through  **prompt**  events by accessing an existing Excel table with an external connection.

```csharp
private void btnApplyPromptParameter_Click(object sender, EventArgs e)
{
    using (ExcelEngine excelEngine = new ExcelEngine())
    {
        IApplication application = excelEngine.Excel;
 
        //Load existing Excel template document with external connection
        IWorkbook workbook = application.Workbooks.Open(DataPathBase + "Template.xlsx");
        IWorksheet worksheet = workbook.Worksheets[0];
 
        //Accessing the query table from Excel table
        QueryTableImpl queryTable = worksheet.ListObjects[0].QueryTable;
 
        //Update Excel query to filter data from various parameter types
        string query = "select * from Employee_Details where Emp_Age = ? AND Country = ?;";
        queryTable.CommandText = query;
 
        //Add a parameter
        IParameter promptParam = queryTable.Parameters.Add("PromptParameter", ExcelParameterDataType.ParamTypeChar);
 
        //Set PROMPT parameter by raising the event SetParam
        promptParam.SetParam(ExcelParameterType.Prompt, "Emp Age");
        promptParam.Prompt += new PromptEventHandler(SetParameter1);
        promptParam.Prompt += new PromptEventHandler(SetParameter2);
 
        //Refresh Excel table to filter data while loading Excel document
        worksheet.ListObjects[0].Refresh();
 
        //Save the workbook
        workbook.SaveAs("Output.xlsx");
    }
}
 
private void SetParameter1(object sender, PromptEventArgs args)
{
    args.Value = 30;
}
 
private void SetParameter2(object sender, PromptEventArgs args) 
{ 
    args.Value = "Argentina"; 
}
```

![Screenshot of applying PROMPT parameter in MS Excel](https://blog.syncfusion.com/wp-content/uploads/2019/07/2_Prompt-parameter-in-MS-Excel.png)

<figcaption>Screenshot of Applying Prompt Parameter in Microsoft Excel</figcaption>

![Excel file generated with PROMPT parameter query](https://blog.syncfusion.com/wp-content/uploads/2019/07/3_Output-file-with-employee-details-filtered-by-Emp_Age.png)

<figcaption>Excel File Generated with Prompt Parameter Query</figcaption>

### Constant parameter

The constant parameter type helps the user define a constant from the code and filter the Excel table. Here, if the data is modified in the database, the filtering is always done for the constant value defined in the code.

The following code example illustrates how to set the parameter through the **constant** type by accessing an existing Excel table with an external connection.

```csharp
private void btnApplyConstantParameter_Click(object sender, EventArgs e)
{
    using (ExcelEngine excelEngine = new ExcelEngine())
    {
        IApplication application = excelEngine.Excel;
 
        //Load existing Excel template document with external connection
        IWorkbook workbook = application.Workbooks.Open(DataPathBase + "Template.xlsx");
        IWorksheet worksheet = workbook.Worksheets[0];
 
        //Accessing the query table from Excel table
        QueryTableImpl queryTable = worksheet.ListObjects[0].QueryTable;
 
        //Update Excel query to filter data from various parameter types
        string query = "select * from Employee_Details where Emp_Age > ?;";
        queryTable.CommandText = query;
 
        //Add a parameter object
        IParameter constParam = queryTable.Parameters.Add("ConstantParameter", ExcelParameterDataType.ParamTypeChar);
 
        //Set CONSTANT parameter
        constParam.SetParam(ExcelParameterType.Constant, 25);
 
        //Refresh Excel table to filter data while loading Excel document
        worksheet.ListObjects[0].Refresh();
 
        //Save the workbook
        workbook.SaveAs("Output.xlsx");
    }
}
```

![Screenshot of applying CONSTANT parameter in Microsoft Excel](https://blog.syncfusion.com/wp-content/uploads/2019/07/4_Constant-parameter-in-MS-Excel.png)

<figcaption>Screenshot of Applying Constant Parameter in Microsoft Excel</figcaption>

![Excel file generated with CONSTANT parameter query](https://blog.syncfusion.com/wp-content/uploads/2019/07/5_Output-of-Excel-document-with-constant-parameter-applied.png)

<figcaption>Excel File Generated with Constant Parameter Query</figcaption>

### Range parameter

Situations may arise where you need to show data from a database based on a cell value in an Excel worksheet. For example, if a cell contains a formula and the value varies for certain cases, the Excel table will reflect this accordingly. The range parameter helps filter data based on the cell values available in a worksheet range.

The following code shows how to set a parameter type to a specific range.

```csharp
private void btnApplyRangeParameter_Click(object sender, EventArgs e)
{
    using (ExcelEngine excelEngine = new ExcelEngine())
    {
        IApplication application = excelEngine.Excel;
 
        //Load existing Excel template document with external connection
        IWorkbook workbook = application.Workbooks.Open(DataPathBase + "Template.xlsx");
        IWorksheet worksheet = workbook.Worksheets[0];
 
        //Accessing the query table from Excel table
        QueryTableImpl queryTable = worksheet.ListObjects[0].QueryTable;
 
        //Update Excel query to filter data from various parameter types
        string query = "select * from Employee_Details where Emp_Age = ?;";
        queryTable.CommandText = query;
 
        //Add a parameter
        IParameter rangeParam = queryTable.Parameters.Add("RangeParameter", ExcelParameterDataType.ParamTypeChar);
 
        //Set RANGE parameter
        rangeParam.SetParam(ExcelParameterType.Range, worksheet.Range["H1"]);
        rangeParam.RefreshOnChange = true;
 
        //Refresh Excel table to filter data while loading Excel document
        worksheet.ListObjects[0].Refresh();
 
        //Save the workbook
        workbook.SaveAs("Output.xlsx");
    }
}
```

![Screenshot of applying RANGE parameter in MS Excel](https://blog.syncfusion.com/wp-content/uploads/2019/06/6_Range-parameter-in-MS-Excel.png)

<figcaption>Screenshot of applying Range Parameter in Microsoft Excel</figcaption>

![Excel file generated with RANGE parameter query](https://blog.syncfusion.com/wp-content/uploads/2019/07/7_Output-of-Excel-document-with-range-parameter-applied.png)

<figcaption>Excel File Generated with Range Parameter Query</figcaption>

## **How to refresh Excel data from a database**

Excel worksheets that are connected to SQL Server as an external data source will fetch data for an Excel table. If data is updated in the database, it is mandatory to refresh the Excel table to update its data. Essential XlsIO allows you to update the data by refreshing the table from its source. Refresh the connection every time, when the data is updated.

Here we invoke the **_Refresh()_** method of the **_IListObject_ ** class to get updated data from the database in an Excel table.

The following code sample shows how to export data from a database to an Excel table.

```csharp
private void btnCreateExcel_Click(object sender, EventArgs e) 
{ 
    using (ExcelEngine excelEngine = new ExcelEngine()) 
    { 
        IApplication application = excelEngine.Excel;  
 
        //Load existing Excel document with an external connection 
        IWorkbook workbook = application.Workbooks.Open(DataPathBase + "Template.xlsx"); 
        IWorksheet worksheet = workbook.Worksheets[0]; 
 
        //Refresh Excel table to update data after loading the Excel document. 
        worksheet.ListObjects[0].Refresh(); 
 
        //Save the workbook
        workbook.SaveAs("Output.xlsx"); 
    } 
}
```

## GitHub Sample

You can download the sample to export data from SQL Server into Excel table in C# [here](https://github.com/SyncfusionExamples/import-data-from-sql-server-to-excel-table-in-c-sharp).

## Conclusion

In short, Excel is mainly used for processing and visualizing data, and [Syncfusion’s Excel (XlsIO) library](https://www.syncfusion.com/excel-framework/net) provides an easy way to export data from SQL Server and filter it at runtime. Use them effectively to generate Excel reports with high performance and process large amounts of data.

For more information about creating external data connections and setting parameters, refer to our documentation on [external data connections.](https://help.syncfusion.com/file-formats/xlsio/working-with-tables#create-a-table-from-external-connection) This feature is supported in .NET Framework platforms such as Windows Forms, WPF, ASP.NET, and ASP.NET MVC.

Take a moment to peruse the [documentation](https://help.syncfusion.com/file-formats/xlsio/working-with-tables#adding-parameters-to-query-in-excel-table), where you’ll find other options and features, all with accompanying code samples. Using the Excel library, you can also export Excel data to [PDF](https://help.syncfusion.com/file-formats/xlsio/excel-to-pdf-conversion), [image](https://help.syncfusion.com/file-formats/xlsio/worksheet-to-image-conversion), [CSV](https://www.syncfusion.com/kb/9092/convert-excel-file-to-csv-in-c-vb-net), [TSV](https://www.syncfusion.com/kb/8556/does-xlsio-support-tsv-files), [HTML](https://help.syncfusion.com/file-formats/xlsio/working-with-excel-worksheet#save-worksheet-as-html), and [ODS](https://help.syncfusion.com/file-formats/xlsio/excel-to-ods-conversion) file formats; [data tables](https://help.syncfusion.com/file-formats/xlsio/working-with-data#exporting-from-worksheet-to-data-table); [collections of objects](https://help.syncfusion.com/file-formats/xlsio/working-with-data#exporting-from-worksheet-to-collection-objects); and more.

If you are new to our Excel library, it is highly recommended that you follow our [Getting Started guide](https://help.syncfusion.com/file-formats/xlsio/getting-started).

Already a Syncfusion user? You can download the product setup from the [Essential Studio Downloads page](https://www.syncfusion.com/account/downloads/studio/). If you’re not yet a Syncfusion user, you can download a free, 30-day trial from [our website](https://www.syncfusion.com/downloads/fileformats/confirm).

If you have any questions or require clarifications about these features, please let us know in the comments below. You can also contact us through our [support forum](https://www.syncfusion.com/forums), [Direct-Trac](https://www.syncfusion.com/support/directtrac), or our [feedback portal](https://www.syncfusion.com/feedback/). We are happy to assist you!

## Related Blog

1. [6 Easy Ways to Export Data to Excel in C#](https://www.syncfusion.com/blogs/post/6-easy-ways-to-export-data-to-excel-in-c-sharp.aspx)

The post [How to Export Data from SQL Server to Excel Table in C#](https://www.syncfusion.com/blogs/post/export-data-from-sql-server-to-excel-in-c-sharp.aspx) appeared first on [Syncfusion Blogs](https://www.syncfusion.com/blogs).