Skip to footer content
USING IRONXL

How to Export SQL Data to Excel Using C# with IronXL

Exporting data from SQL Server to Microsoft Excel is a common requirement for .NET developers building reporting systems, data analysis tools, and business applications. This tutorial demonstrates how to export SQL data to Excel using C# with IronXL, a powerful Excel library that simplifies the entire process without requiring Microsoft Office installation.

Start your free trial to follow along with the code examples below.

Get stated with IronXL now.
green arrow pointer

What is the Best Way to Export Data from a SQL Server Database?

The most efficient approach to export data from SQL Server to an Excel file involves three steps: establish a database connection, retrieve data into a DataTable, and write the data to an Excel worksheet using IronXL. Unlike Microsoft Interop solutions, IronXL operates independently and handles large datasets with excellent performance.

How Do You Connect to SQL Server and Retrieve Data?

Before you can export SQL data, you need to establish a connection and execute a SQL query to fill a DataTable. The connection string contains the SQL Server database credentials and server information required to access your data.

You will need to import the following namespaces in your Visual Studio project:

using IronXL;
using System.Data;
using System.Data.SqlClient;
// Define connection string for SQL Server
string connectionString = @"Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True";
// SQL query to retrieve data from SQL Server table
string sql = "SELECT * FROM Customers";
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    // Use SqlDataAdapter to fill DataTable with query results
    SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
    DataTable dt = new DataTable();
    adapter.Fill(dt);
    // Create new workbook and worksheet
    WorkBook workBook = WorkBook.Create();
    WorkSheet workSheet = workBook.CreateWorkSheet("CustomerData");
    // Export DataTable to Excel worksheet with column names
    int rowIndex = 1;
    // Write column headers from DataTable
    for (int j = 0; j < dt.Columns.Count; j++)
    {
        workSheet.SetCellValue(0, j, dt.Columns[j].ColumnName);
    }
    // Fill worksheet with data values
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        for (int j = 0; j < dt.Columns.Count; j++)
        {
            string cellValue = dt.Rows[i][j].ToString();
            workSheet.SetCellValue(rowIndex, j, cellValue);
        }
        rowIndex++;
    }
    // Save Excel file in xlsx format
    workBook.SaveAs("CustomerExport.xlsx");
}
using IronXL;
using System.Data;
using System.Data.SqlClient;
// Define connection string for SQL Server
string connectionString = @"Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True";
// SQL query to retrieve data from SQL Server table
string sql = "SELECT * FROM Customers";
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    // Use SqlDataAdapter to fill DataTable with query results
    SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
    DataTable dt = new DataTable();
    adapter.Fill(dt);
    // Create new workbook and worksheet
    WorkBook workBook = WorkBook.Create();
    WorkSheet workSheet = workBook.CreateWorkSheet("CustomerData");
    // Export DataTable to Excel worksheet with column names
    int rowIndex = 1;
    // Write column headers from DataTable
    for (int j = 0; j < dt.Columns.Count; j++)
    {
        workSheet.SetCellValue(0, j, dt.Columns[j].ColumnName);
    }
    // Fill worksheet with data values
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        for (int j = 0; j < dt.Columns.Count; j++)
        {
            string cellValue = dt.Rows[i][j].ToString();
            workSheet.SetCellValue(rowIndex, j, cellValue);
        }
        rowIndex++;
    }
    // Save Excel file in xlsx format
    workBook.SaveAs("CustomerExport.xlsx");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

How to Export SQL Data to Excel Using C# with IronXL: Image 1 - Generated Excel file

This code creates an Excel file with properly formatted column headers derived from your SQL Server table structure. The DataTable dt stores the query results, which are then written to each Excel sheet cell systematically. The following code demonstrates the add method pattern for populating worksheet cells. IronXL supports both xls and xlsx formats for maximum compatibility with Microsoft Office applications.

How Can You Export Data Using an ASP.NET Export Button?

For web applications, you'll typically trigger the export when a user clicks an export button. The following code shows how to handle the button click event and initiate a file download using Response.AddHeader for content disposition.

using IronXL;
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI;
public partial class ExportPage : Page
{
    private void ExportButton_Click(object sender, EventArgs e)
    {
        string connectionString = @"Data Source=localhost;Initial Catalog=Sales;Integrated Security=True";
        try
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                // Execute SQL query to get data from SQL server
                SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Orders", connection);
                DataSet dataSet = new DataSet();
                adapter.Fill(dataSet);
                // Create Excel workbook from DataSet - each table becomes a sheet
                WorkBook workBook = WorkBook.Create();
                WorkBook.LoadWorkSheetsFromDataSet(dataSet, workBook);
                // Convert to byte array for download
                byte[] fileBytes = workBook.ToByteArray();
                string filename = "OrdersExport.xlsx";
                // Set response headers for file download
                Response.Clear();
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename=" + filename);
                Response.BinaryWrite(fileBytes);
                Response.End();
            }
        }
        catch (Exception ex)
        {
            // Handle any errors during export
            Response.Write("Export error: " + ex.Message);
        }
    }
}
using IronXL;
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI;
public partial class ExportPage : Page
{
    private void ExportButton_Click(object sender, EventArgs e)
    {
        string connectionString = @"Data Source=localhost;Initial Catalog=Sales;Integrated Security=True";
        try
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                // Execute SQL query to get data from SQL server
                SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Orders", connection);
                DataSet dataSet = new DataSet();
                adapter.Fill(dataSet);
                // Create Excel workbook from DataSet - each table becomes a sheet
                WorkBook workBook = WorkBook.Create();
                WorkBook.LoadWorkSheetsFromDataSet(dataSet, workBook);
                // Convert to byte array for download
                byte[] fileBytes = workBook.ToByteArray();
                string filename = "OrdersExport.xlsx";
                // Set response headers for file download
                Response.Clear();
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename=" + filename);
                Response.BinaryWrite(fileBytes);
                Response.End();
            }
        }
        catch (Exception ex)
        {
            // Handle any errors during export
            Response.Write("Export error: " + ex.Message);
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Example Export Button

How to Export SQL Data to Excel Using C# with IronXL: Image 2 - Example export button ui

Output

How to Export SQL Data to Excel Using C# with IronXL: Image 3 - Generated file

The object sender and EventArgs e parameters are standard for ASP.NET event handlers. Unlike Microsoft Interop which requires object misValue for missing parameters, IronXL uses a cleaner API. When the user clicks the export button, this private void method executes the database query, creates the Excel document, and triggers the file download through the browser.

How Do You Import Data and Create Excel Files with Column Headers?

IronXL provides multiple methods to create Excel files and import data efficiently. The LoadWorkSheetsFromDataSet method accepts DataTable collections and automatically preserves column names as headers in your Excel worksheet. This approach works seamlessly with System.Data objects and Microsoft SQL Server.

using IronXL;
using System.Data;
using System.Data.SqlClient;
// Connection to SQL database
string connectionString = @"Data Source=.;Initial Catalog=Inventory;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    // Query multiple tables from database
    SqlDataAdapter productsAdapter = new SqlDataAdapter("SELECT * FROM Products", connection);
    SqlDataAdapter categoriesAdapter = new SqlDataAdapter("SELECT * FROM Categories", connection);
    DataSet dataSet = new DataSet();
    productsAdapter.Fill(dataSet, "Products");
    categoriesAdapter.Fill(dataSet, "Categories");
    // Create new workbook and load all tables
    WorkBook workBook = WorkBook.Create();
    WorkBook.LoadWorkSheetsFromDataSet(dataSet, workBook);
    // Save as xlsx file
    workBook.SaveAs("InventoryReport.xlsx");
}
using IronXL;
using System.Data;
using System.Data.SqlClient;
// Connection to SQL database
string connectionString = @"Data Source=.;Initial Catalog=Inventory;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    // Query multiple tables from database
    SqlDataAdapter productsAdapter = new SqlDataAdapter("SELECT * FROM Products", connection);
    SqlDataAdapter categoriesAdapter = new SqlDataAdapter("SELECT * FROM Categories", connection);
    DataSet dataSet = new DataSet();
    productsAdapter.Fill(dataSet, "Products");
    categoriesAdapter.Fill(dataSet, "Categories");
    // Create new workbook and load all tables
    WorkBook workBook = WorkBook.Create();
    WorkBook.LoadWorkSheetsFromDataSet(dataSet, workBook);
    // Save as xlsx file
    workBook.SaveAs("InventoryReport.xlsx");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

How to Export SQL Data to Excel Using C# with IronXL: Image 4 - Generated file with column headers

This approach efficiently handles multiple SQL Server tables, creating separate worksheet tabs within a single workbook. For applications using stored procedures, simply replace the inline SQL query with your procedure call using CommandType.StoredProcedure.

What About Web Applications with HTML Markup?

In ASP.NET applications where the HTML markup consists of buttons and data grids, IronXL integrates seamlessly. Your page's HTML markup consists of standard web controls that trigger server-side export operations, while IronXL handles all Excel generation without dependencies on Microsoft Office.

For detailed guidance on exporting DataSet and DataTable objects, visit the IronXL documentation.

Conclusion

Exporting SQL data to Excel using C# becomes straightforward with IronXL. The library eliminates complex Interop dependencies while providing robust support for DataTable, DataSet, and direct database integration. Whether building console applications or web-based reporting systems with file download capabilities, IronXL delivers reliable Excel file generation.

Purchase a license for production deployment, or continue exploring with a free trial to test the full capabilities of this Excel library in your .NET projects.

Frequently Asked Questions

How can I export SQL data to Excel using C#?

You can export SQL data to Excel using C# by leveraging IronXL, a powerful Excel library. It simplifies the process and does not require Microsoft Office installation.

What are the prerequisites for using IronXL to export SQL data?

To use IronXL for exporting SQL data, you need to have a basic understanding of C#, access to a SQL Server, and the IronXL library installed in your development environment.

Do I need Microsoft Office installed to export SQL data to Excel with IronXL?

No, IronXL allows you to export SQL data to Excel without needing Microsoft Office installed on your system.

Can IronXL handle large datasets when exporting SQL data to Excel?

Yes, IronXL is capable of handling large datasets efficiently, making it suitable for exporting extensive SQL data to Excel.

Is IronXL compatible with all versions of SQL Server?

IronXL is designed to work with various versions of SQL Server, ensuring compatibility and ease of use across different environments.

What are some use cases for exporting SQL data to Excel?

Exporting SQL data to Excel is useful for building reporting systems, data analysis tools, and business applications where data needs to be easily accessible and shareable in a widely-used format.

Does IronXL support formatting options for Excel files?

Yes, IronXL provides a range of formatting options, allowing you to customize the appearance and structure of your exported Excel files.

How does IronXL simplify the process of exporting SQL data to Excel?

IronXL simplifies the export process by providing intuitive methods for connecting to SQL Server, retrieving DataTable records, and generating Excel files without the need for complex setup or additional software.

Jordi Bardia
Software Engineer
Jordi is most proficient in Python, C# and C++, when he isn’t leveraging his skills at Iron Software; he’s game programming. Sharing responsibilities for product testing, product development and research, Jordi adds immense value to continual product improvement. The varied experience keeps him challenged and engaged, and he ...
Read More