In this article I will explain with an example, how to export Grid (GridView) to Excel file using jQuery in ASP.Net MVC Razor.
Database
I have made use of the following table Customers with the schema as follows. CustomerId is an Auto-Increment (Identity) column.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Entity Framework Model
Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, all the records from the Customers table is returned to the View as a Generic List collection.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
CustomersEntities entities = new CustomersEntities();
return View(entities.Customers.ToList());
}
}
View
Inside the View, in the very first line the Customer Entity is declared as IEnumerable which specifies that the Model will be available as a Collection.
For displaying the Table records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the Customer Model objects.
Inside the jQuery document ready event handler, the Export Button has been assigned a jQuery Click event handler.
@model IEnumerable<Customer>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table id="tblCustomers" class="table" cellpadding="0" cellspacing="0">
<tr>
<th style="width:80px">Customer Id</th>
<th style="width:120px">Name</th>
<th style="width:100px">Country</th>
</tr>
@foreach (Customer customer in Model)
{
<tr>
<td>@customer.CustomerId</td>
<td>@customer.Name</td>
<td>@customer.Country</td>
</tr>
}
</table>
<br/>
<input type="submit" id="btnExport" value="Export"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="~/Scripts/table2excel.js"></script>
<script type="text/javascript">
$(function () {
$("#btnExport").click(function () {
$("#tblCustomers").table2excel({
filename: "Table.xls"
});
});
});
</script>
</body>
</html>
Screenshots
The Grid (GridView)
Excel file being downloaded when Export Button is clicked
The generated Excel file
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Downloads