Export HTML Table to Excel using jQuery in ASP.Net MVC

Export HTML Table to Excel using jQuery in ASP.Net MVC

In this article, HTML Table will be exported to Excel file using the jQuery table2excel plugin in ASP.Net MVC Razor

In view

 

@model IEnumerable<Customer>
 
@{
    Layout = null;
}
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Export to excel</title>
</head>
<body>
    <table id="tblCustomer" class="table" cellpadding="0" cellspacing="0">
        <tr>
            <th style="width:70px">Id</th>
            <th style="width:120px">Name</th>
            <th style="width:100px">Country</th>
        </tr>
        @foreach (Customer customer in Model)
        {
            <tr>
                <td class="CustomerId">@customer.CustomerId</td>
                <td class="Name">@customer.Name</td>
                <td class="Country">@customer.Country</td>
            </tr>
        }
    </table>
    <br/>
    <input type="submit" id="btn_Export" value="Export to excel"/>
    <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 () {
            $("#btn_Export").click(function () {
                $("#tblCustomer").table2excel({
                    filename: "Table.xls"
                });
            });
        });
    </script>
</body>
</html>

Controller

 

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        CustomersEntities data = new CustomersEntities();
        return View(data .Customers.ToList());
    }
}

2020-04-30