In this article I will explain with an example, how to export to Excel file in ASP.Net MVC Razor.
The data from the database is fetched using Entity Framework and then the data is exported and downloaded as Microsoft Excel file using ClosedXML Excel Library which is a wrapper for OpenXml Excel library.
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Installing and adding reference of ClosedXML Library
In order to install and add reference of ClosedXML library, you will need to:-
1. Right Click the Project in Solution Explorer and click Manage NuGet Packages from the Context Menu.
Export to Excel in ASP.Net MVC
2. Now you will need to look for ClosedXML package and once found, you need to click the Install Button.
Export to Excel in ASP.Net MVC
Configuring and connecting Entity Framework to database
Now I will explain the steps to configure and add Entity Framework and also how to connect it with the database.
You will need to add Entity Data Model to your project by right clicking the Solution Explorer and then click on Add and then New Item option of the Context Menu.
Export to Excel in ASP.Net MVC
From the Add New Item window, select ADO.NET Entity Data Model and set its Name as NorthwindModel and then click Add.
Export to Excel in ASP.Net MVC
Then the Entity Data Model Wizard will open up where you need to select EF Designer database option.
Export to Excel in ASP.Net MVC
Now the wizard will ask you to connect and configure the Connection String to the database.
Export to Excel in ASP.Net MVC
You will need to select the
1.     SQL Server Instance
2.     Database
And then click Test Connection to make sure all settings are correct.
Export to Excel in ASP.Net MVC
Once the Connection String is generated, click Next button to move to the next step.
Export to Excel in ASP.Net MVC
Next you will need to choose the Entity Framework version to be used for connection.
Export to Excel in ASP.Net MVC
Now you will need to choose the Tables you need to connect and work with Entity Framework. Here Customers Table is selected.
Export to Excel in ASP.Net MVC
The above was the last step and you should now have the Entity Data Model ready with the Customers Table of the Northwind Database.
Export to Excel in ASP.Net MVC
You will need to import the following namespaces.
using System.IO;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ClosedXML.Excel;
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, the Top 10 Customer records are fetched and returned to the View.
Action method for handling the Excel File Export and Download operation
This Action method is executed when the Export Submit button is clicked.
Note: The following Action method performs File Download and hence the return type is set to FileResult.
The Top 10 Customer records are fetched from the Customers Table using Entity Framework and are added to a dynamic DataTable. Then the DataTable is added to the Worksheets collection of the ClosedXML’s XLWorkbook object.
Then XLWorkbook object is saved to a MemoryStream object which then is converted to Byte Array and exported and downloaded as Excel file using the File function.
public class HomeController : Controller
    // GET: Home
    public ActionResult Index()
        NorthwindEntities entities = new NorthwindEntities();
        return View(from customer in entities.Customers.Take(10)
                    select customer);
    public FileResult Export()
        NorthwindEntities entities = new NorthwindEntities();
        DataTable dt = new DataTable("Grid");
        dt.Columns.AddRange(new DataColumn[4] { new DataColumn("CustomerId"),
                                            new DataColumn("ContactName"),
                                            new DataColumn("City"),
                                            new DataColumn("Country") });
        var customers = from customer in entities.Customers.Take(10)
                        select customer;
        foreach (var customer in customers)
            dt.Rows.Add(customer.CustomerID, customer.ContactName, customer.City, customer.Country);
        using (XLWorkbook wb = new XLWorkbook())
            using (MemoryStream stream = new MemoryStream())
                return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Grid.xlsx");
Now you will need to Right Click inside the Controller class and click on the Add View option in order to create a View for the Controller.
The Name of the View is set to Index, the Template option is set to Empty, the Model class is set to Customer Entity (the one we have generated using Entity Framework) and finally the Data context class is set to NorthwindEntities.
Export to Excel in ASP.Net MVC
Inside the View, in the very first line the Customer Entity is declared as IEnumerable which specifies that it will be available as a Collection.
For displaying the records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the Customer records.
Finally there’s an HTML Submit button enclosed inside a Form with the Action method specified as Export.
When this Button will be clicked, the Grid (Html Table) data will be exported and downloaded as Excel file.
@model IEnumerable<Export_Excel_MVC.Customer>
    Layout = null;
<!DOCTYPE html>
    <meta name="viewport" content="width=device-width"/>
    <table cellpadding="0" cellspacing="0">
            <th>Contact Name</th>
        @foreach (Customer customer in Model)
    @using (Html.BeginForm("Export", "Home", FormMethod.Post))
        <input type="submit" value="Export"/>
Grid (Html Table)
Export to Excel in ASP.Net MVC
Exported Excel File
Export to Excel in ASP.Net MVC