In this article I will explain with an example, how to export SQL data to Excel file with Column Headers (Column Names) in ASP.Net Core (.Net Core) MVC.
 
 

Install ClosedXML package

In order to install ClosedXML library using Nuget, please refer my article Install ClosedXML Nuget Package.
 
 

Database

I have made use of the following table Customers with the schema as follows.
ASP.Net Core: Export SQL data to Excel with Column Headers (Column Names)
 
I have already inserted few records in the table.
ASP.Net Core: Export SQL data to Excel with Column Headers (Column Names)
 
Note: You can download the database table SQL by clicking the download link below.
            Download SQL file
 
 

Connection Strings in AppSettings.json file

The connection string to the Database and Excel file are saved in the AppSettings.json file.
Note: For more details about saving and reading connection strings in AppSettings.json file, please refer .Net Core 7: Read Connection String from AppSettings.json file.
 
The DataSource property has been assigned a Placeholder {0}, which will be replaced by actual path of the File.
{
  "ConnectionStrings": {
    "constr": "Data Source=.\\SQL2022;Initial Catalog= AjaxSamples;Uid=sa;Pwd=pass@123;"
  }
}
 
 

Namespaces

You will need to import the following namespaces.
using System.IO;
using System.Data;
using System.Data.SqlClient;
using ClosedXML.Excel;
 
 

Controller

Inside the Controller, first the public property of IConfiguration interface is created.
Then, the IConfiguration interface is injected into the Constructor (IndexModel) using Dependency Injection method and the injected object is assigned to the public property of IConfiguration interface.
The Controller consists of following Action methods.

Action method for handling GET operation

Inside this Action method, simply the View is returned.
 

Action method for handling POST operation

This Action method is executed when the Export Button is clicked.
Inside this Action method, an object of XLWorkbook is created and the GetCustomers method (explained later) is called.
The records returned from the GetCustomers method (explained later) are stored into a DataTable object which is added as Worksheet collection to the XLWorkbook object.
Finally, the XLWorkbook object is saved to a MemoryStream class object then it is converted to BYTE Array and exported and downloaded as Excel file using the File function.
 

GetCustomers

Inside this method, first the connection is read from the ConnectionStrings section of the AppSettings.json file.
Then, a connection to the database is established using the SqlConnection class.
The records are fetched using SqlDataAdapter class and stored into a DataSet object which is returned.
Note: For more details on SqlDataAdapter, please refer my article ASP.Net Core MVC: Implementing SqlDataAdapter.
 
public class HomeController : Controller
{
    public IConfiguration Configuration { getset; }
 
    public HomeController(IConfiguration _configuration)
    {
        this.Configuration = _configuration;
    }
 
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public IActionResult Export()
    {
        using (XLWorkbook wb = new XLWorkbook())
        {
            DataTable dt = this.GetCustomers().Tables[0];
            wb.Worksheets.Add(dt);
            using (MemoryStream stream = new MemoryStream())
            {
                wb.SaveAs(stream);
                return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Customers.xlsx");
            }
        }
    }
 
    private DataSet GetCustomers()
    {
        DataSet ds = new DataSet();
        string constr = this.Configuration.GetSection("ConnectionStrings")["MyConn"];
        string sql "SELECT CustomerId, Name, Country FROM Customers";
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter(sql, con))
            {
                sda.Fill(ds);
            }
        }
 
        return ds;
    }
}
 

View

HTML Markup

The View consists of an HTML Form with following ASP.Net Tag Helpers attributes.
asp-action – Name of the Action. In this case the name is Export.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The View also consists of a Submit Button, which when clicked the Form is submitted.
@addTagHelper*,Microsoft.AspNetCore.Mvc.TagHelpers
@{
     Layout = null;
}
 
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <form method="post" asp-controller="Home" asp-action="Export">
        <input type="submit" value="Export" />
    </form>
</body>
</html>
 
 

Screenshots

Form

ASP.Net Core: Export SQL data to Excel with Column Headers (Column Names)
 

The Excel File

ASP.Net Core: Export SQL data to Excel with Column Headers (Column Names)
 
 

Demo

 
 

Downloads



Other available versions