How to Export Data from SQL Server to Excel Table in C# | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (173).NET Core  (29).NET MAUI  (203)Angular  (107)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (211)BoldSign  (13)DocIO  (24)Essential JS 2  (106)Essential Studio  (200)File Formats  (65)Flutter  (132)JavaScript  (219)Microsoft  (118)PDF  (81)Python  (1)React  (98)Streamlit  (1)Succinctly series  (131)Syncfusion  (897)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (50)Windows Forms  (61)WinUI  (68)WPF  (157)Xamarin  (161)XlsIO  (35)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (146)Chart  (127)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (618)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (39)Extensions  (22)File Manager  (6)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (501)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (42)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (381)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (17)Web  (582)What's new  (323)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Excel Table with Parameter Query

How to Export Data from SQL Server to Excel Table in C#

Microsoft Excel is known for storing, analyzing, and visualizing data. Databases 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 helps you export data from 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.

Enjoy a smooth experience with Syncfusion’s Excel Library! Get started with a few lines of code and without Microsoft or interop dependencies.

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:

select * from Employee_Details;
Data Exported from SQL Server to Excel
Data Exported from SQL Server to Excel

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 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 an SQL Server database and a query string to retrieve data from an 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.

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("Output.xlsx");

        workbook.SaveAs(excelStream);
        excelStream.Dispose();
    }
}

Handle Excel files like a pro with Syncfusion’s C# Excel Library, offering well-documented APIs for each functionality.

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:

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.

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("../../Data/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
Screenshot of Applying Prompt Parameter in Microsoft Excel
Excel file generated with PROMPT parameter query
Excel File Generated with Prompt Parameter Query

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.

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("../../Data/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
Screenshot of Applying Constant Parameter in Microsoft Excel
Excel file generated with CONSTANT parameter query
Excel File Generated with Constant Parameter Query

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.

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("../../Data/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
Screenshot of applying Range Parameter in Microsoft Excel

Excel file generated with RANGE parameter query
Excel File Generated with Range Parameter Query

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.

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("../../Data/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 an Excel table in C# here.

Don't settle for ordinary spreadsheet solutions. Switch to Syncfusion and upgrade the way you handle Excel files in your apps!

Conclusion

In short, Excel is mainly used for processing and visualizing data, and Syncfusion’s Excel (XlsIO) library 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. 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, where you’ll find other options and features, all with accompanying code samples. Using the Excel library, you can also export Excel data to PDFimageCSVTSV, HTML, and ODS file formats; data tablescollections of objects; and more.

If you are new to our Excel library, it is highly recommended that you follow our Getting Started guide.

Already a Syncfusion user? You can download the product setup from the Essential Studio Downloads page. If you’re not yet a Syncfusion user, you can download a free, 30-day trial from our website.

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, support portal, or our feedback portal. We are happy to assist you!

Related Blogs

Tags:

Share this post:

Comments (2)

[…] How to Import Data from SQL Server to Excel Table in C# (Johnson Manohar) […]

Krishna Rao Vasudevan
Krishna Rao Vasudevan

I shall be very grateful to your posting notes on import from sql server to excel

Comments are closed.

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed