In this article I will explain with an example, how to export WebGrid to Word document in ASP.Net MVC.
The WebGrid will be populated from database using Entity Framework and then the WebGrid will be sent as HTML string to the Controller which will be exported to Word document in ASP.Net MVC.
 
 
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
 
 
Entity Framework Model
Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Note: For beginners in ASP.Net MVC and Entity Framework, please refer my article ASP.Net MVC: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework.
 
ASP.Net MVC: Export WebGrid to Word Document
 
Namespaces
You will need to import the following namespace.
using System.Text;
 
 
Controller
The Controller consists of following two Action methods.
Action method for handling GET operation
Inside this Action method, the Top 10 records from the Customers Table are fetched using Entity Framework and returned to the View.
 
Action method for handling the Word document 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 HTML of the WebGrid sent from the View is extracted from the GridHtml parameter.
While posting HTML content from View to Controller, you will get error A potentially dangerous Request.Form value was detected from the client.
For more details on resolving the error, please refer my article [Solution] ASP.Net MVC A potentially dangerous Request.Form value was detected from the client.
Then, the HTML string is read and converted to a Byte Array using the GetBytes method of Encoding class.
Finally, the Byte Array is exported and downloaded as Word document using the File function.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        NorthwindEntities entities = new NorthwindEntities();
        return View(entities.Customers.Take(10).ToList());
    }
 
    [HttpPost]
    [ValidateInput(false)]
    public FileResult Export(string GridHtml)
    {
        return File(Encoding.UTF8.GetBytes(GridHtml), "application/vnd.ms-word", "Grid.doc");
    }
}
 
 
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.
Displaying the records
The WebGrid is initialized with the Model i.e. IEnumerable collection of Customer Entity class objects as source.
For displaying the records, the WebGrid is rendered using GetHtml function which renders the WebGrid using Model.
Note: For more details on using WebGrid, please refer my article WebGrid Step By Step Tutorial with example in ASP.Net MVC.
 
In order to export WebGrid with formatting, in-line CSS styles are applied to the WebGrid and its Header and Data rows using jQuery.
 
Exporting the WebGrid to Word document
Below the WebGrid, there is an HTML Submit button enclosed inside a Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Export.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
Also, there is an HTML Hidden Field element which will be used to send the HTML content of the WebGrid to the Controller’s Action method.
When the Export button is clicked, first the HTML of the WebGrid is extracted and set into the Hidden Field element and finally, the Form is submitted.
@model IEnumerable<Export_WebGrid_Word_MVC.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>
    <h4>Customers</h4>
    <hr />
    <div id="Grid">
        @webGrid.GetHtml(
        htmlAttributes: new { @id = "WebGrid" },
        columns: webGrid.Columns(
                 webGrid.Column("CustomerID", "CustomerID"),
                 webGrid.Column("ContactName", "ContactName"),
                 webGrid.Column("City", "City"),
                 webGrid.Column("Country", "Country")))
    </div>
    <br /><br />
    @using (Html.BeginForm("Export", "Home", FormMethod.Post))
    {
        <input type="hidden" name="GridHtml" />
        <input type="submit" id="btnSubmit" value="Export" />
    }
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            // Add CSS to the Table for formatting.
            $("#Grid table").attr("cellpadding", "5");
            $("#Grid table").css({ "border-collapse": "collapse", "border": "1px solid #ccc" });
            $("#Grid th").css({ "background-color": "#B8DBFD", "border": "1px solid #ccc" });
            $("#Grid td").css({ "border": "1px solid #ccc" });
 
            // Assign Click event to Button.
            $("#btnSubmit").click(function () {
                $("input[name='GridHtml']").val($("#Grid").html());
            });
        });
    </script>
</body>
</html>
 
 
Screenshots
WebGrid
ASP.Net MVC: Export WebGrid to Word Document
 
Exported Word document
ASP.Net MVC: Export WebGrid to Word Document
 
 
Downloads