Export Webgrid Data To Microsoft Excel In ASP.NET MVC 5

Hi again everyone. In this tutorial, I am going to explain how to export Webgrid data into Microsoft Excel sheets. If you are new to Webgrid, please refer to  the links of the posts, given below, to understand the basics of Webgrid.

If you have gone through these tutorials, you will get a basic understanding of Webgrid implementation. In this tutorial, I am going to use the code of the previous posts. I have implemented the screenshots given below of the Webgrid in the previous posts.

table

Exporting Webgrid to Excel in ASP.NET MVC

  1. Create Visual Studio Application in (2013 or 2015).
  2. Please refe to this tutorial Webgrid implementation in ASP.NET MVC5 Application. I am using the code in this tutorial, without creating a new Application.
  3. I am adding an extra code to implement exporting the data.
  4. Add ActionLink, given below, in an Index View, as shown below:
    1. <!--Create a link button to export data-->  
    2.  @Html.ActionLink("Export to Excel", "PrintExcel", "Home", new { @class="btn btn-success"})  
    3. <br/>  
  5. The complete code of the View is shown below:

    Index.cshtml
    1. @model List<WebGridinMVC5.Models.UserTable>  
    2. @{  
    3.     ViewBag.Title = "www.mitechdev.com";  
    4.     //create object for webgrid to use Webgrid helper  
    5.     var grid = new WebGrid(source: Model, canPage: true, rowsPerPage: 7);  
    6.     //pager  
    7.     grid.Pager(WebGridPagerModes.All);  
    8.  }     
    9. <h2>Fetching and displaying data from server in WebGrid</h2><br/>  
    10. <!--Create a link button to export data-->  
    11.  @Html.ActionLink("Export to Excel", "PrintExcel", "Home", new { @class="btn btn-success"})  
    12. <br/>  
    13. <!--web grid styles starts-->  
    14. <style type="text/css">  
    15.     /*styles for altering rows*/  
    16.     .webgrid-row-style {  
    17.         padding: 3px 7px 2px;  
    18.     }  
    19.      .webgrid-alternating-row {  
    20.         background-color: #EAF2D3;  
    21.         padding: 3px 7px 2px;  
    22.     }  
    23. </style>  
    24. <!--web grid styles Ends-->  
    25. <!--web grid display element-->  
    26. <div id="webgrid">  
    27.     @grid.GetHtml(  
    28.     //styles class for table  
    29.     //here i used bootstrap table templates  
    30.             tableStyle: "table table-responsive backcolor",  
    31.             headerStyle:"wedgrid-header",  
    32.             footerStyle:"webgrid-footer",  
    33.             alternatingRowStyle:"webgrid-alternating-row",  
    34.             rowStyle:"webgrid-row-style",  
    35.             //binding table column to the grid  
    36.             columns:grid.Columns(  
    37.             grid.Column(header:"Serial No",format:@<text><div>@(item.WebGrid.Rows.IndexOf(item)+1)</div></text>),  
    38.             grid.Column(columnName:"Name",header:"Name"),  
    39.             grid.Column(header:"Email", format:@<text><a href="mailto:@item.Email">@item.Email</a></text>),  
    40.     grid.Column(columnName:"PhoneNumber",header:"Phone No"),  
    41.             grid.Column(header:"Is Active", format:@<text><input type="checkbox" checked="@item.Status" disabled="disabled" /></text>)  
    42.             )  
    43.     )  
    44. </div>  
  6. You can get the code, shown above, from the previous post's links also (I specified above).

Create method to Export the Data into Excel

  1. Now, add a method to export the data into Microsoft Excel format. When you click 'Export to Excel' button in an Index view page this method (PrintExcel) gets the grid data from the Server and exports it to Excel Sheet.

  2. Replace the HomeController.cs file with the code, given below:

    HomeController.cs
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Web.Mvc;  
    6. using System.Web.Helpers;  
    7. using WebGridinMVC5.Models;  
    8.   
    9. namespace WebGridinMVC5.Controllers  
    10. {  
    11.     public class HomeController : Controller  
    12.     {  
    13.         //Fetch data from database  
    14.         public ActionResult Index()  
    15.         {  
    16.             List lst = new List();  
    17.             using (DatabaseEntities db = new DatabaseEntities())  
    18.             {  
    19.                 lst = db.UserTables.ToList();  
    20.             }  
    21.             //I am passing data ti view through model binding  
    22.             return View(lst);  
    23.           
    24.      }  
    25.         //Added method to controller.  
    26.         //method to export data to Excel  
    27.         public void PrintExcel()  
    28.         {  
    29.             List exceldata = new List();  
    30.             using (DatabaseEntities db = new DatabaseEntities())  
    31.             {  
    32.                 exceldata = db.UserTables.ToList();  
    33.             }  
    34.             //create object to webgrid  
    35.             WebGrid grid = new WebGrid(source: exceldata,canPage:false, canSort: false);  
    36.             string gridData = grid.GetHtml(  
    37.             columns: grid.Columns(  
    38.                             grid.Column("UserID""UserID"),  
    39.                             grid.Column("Name""Name"),  
    40.                             grid.Column("Email""Email"),  
    41.                             grid.Column("PhoneNumber""PhoneNumber"),  
    42.                             grid.Column("Status""Status")  
    43.                             )).ToString();  
    44.                 Response.ClearContent();  
    45.             //give name to excel sheet.  
    46.                 Response.AddHeader("content-disposition""attachment; filename=UserData.xls");  
    47.             //specify content type  
    48.                 Response.ContentType = "application/excel";  
    49.             //write excel data using this method   
    50.                 Response.Write(gridData);  
    51.                 Response.End();  
    52.         }  
    53.  }  
    54. }  
  3. Now, run the Application and see the output.

    output

  4. Now, click on "Export to Excel" and you will get the Window, as shown below:

    window

Conclusion: I hope, this blog may be helpful for many readers.