In this article I will explain with an example, how to export WebGrid to Excel file using jQuery in ASP.Net MVC Razor.
The WebGrid’s HTML Table will be exported (converted) to Excel file using the jQuery table2excel plugin 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 the 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.
The WebGrid is initialized with the Model i.e. IEnumerable collection of Customer Entity class objects as source.
Inside the jQuery document ready event handler, the Export Button has been assigned a jQuery click event handler.
When the Export Button is clicked, the jQuery table2excel plugin is applied to the WebGrid’s HTML Table and the WebGrid is converted (exported) to Excel file. The jQuery table2excel plugin accepts filename parameter which sets the name of the Excel file.
@model IEnumerable<Customer>
@{
Layout = null;
WebGrid webGrid = new WebGrid(source: Model, canSort: false, canPage: false);
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
@webGrid.GetHtml(
htmlAttributes: new { @id = "WebGrid" },
columns: webGrid.Columns(
webGrid.Column("CustomerId", "Customer Id"),
webGrid.Column("Name", "Name"),
webGrid.Column("Country", "Country")))
<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 () {
$("#WebGrid").table2excel({
filename: "Table.xls"
});
});
});
</script>
</body>
</html>
Screenshots
The WebGrid
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