Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export filtered results to excel in MVC 4 (no web form)

I am unable to export the filtered results to an Excel file. I am just learning ASP.Net and MVC.

I have looked at the suggestion here, but I can't get it to work. I am not very sure how to use the EditorTemplate mentioned in another link.

Currently, when I export, all the data gets exported regardless of the filter. How do I export what is displayed on the view to an Excel file, without using web forms?

Thank you..

Here is my view, Index.cshtml:

@model IEnumerable<ExportToExcel.Models.Student>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
    @using (Html.BeginForm("Index","Student",FormMethod.Get))
    {
        <p>
            Name: @Html.TextBox("NameSearch")
            <input type="submit" value="Search" />
            @Html.ActionLink("Export to Excel","ExportToExcel")
        </p>
    }
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Age)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Marks)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Age)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Marks)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
            @Html.ActionLink("Details", "Details", new { id = item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.ID })
        </td>
    </tr>
}

</table>

In my controller, I have implemented the followings:

public ActionResult Index(string nameSearch)
{
    var students = from m in db.Students
                     select m;

    if (!String.IsNullOrEmpty(nameSearch))
    {
        students = students.Where(n => n.Name.Contains(nameSearch));
    }

    return View(students);
}

public ActionResult ExportToExcel()
{
    GridView gv = new GridView();

    //if (!String.IsNullOrEmpty(nameSearch))
    //{
    //    gv.DataSource = db.Students.Where(n => n.Name.Contains(nameSearch)).ToList();
    //}
    //else
    //{
    //    gv.DataSource = db.Students.ToList();
    //}
    gv.DataSource = db.Students.ToList();
    gv.DataBind();

    Response.Clear();
    Response.Buffer = true;
    Response.ContentType = "application/ms-excel";
    Response.AddHeader("content-disposition", "attachment;filename=StudentList.xls");
    Response.Charset = "";

    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    gv.RenderControl(htw);

    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();

    return RedirectToAction("Index");
}
like image 306
moongster Avatar asked Oct 16 '25 10:10

moongster


2 Answers

Ok, managed to find an answer. Original link.

Basically, store the search result in session. Then, retrieve the list from session during export.

like image 79
moongster Avatar answered Oct 19 '25 00:10

moongster


     public ActionResult ExportExcel()

    {

        var EmployeeList = (List<Employee>)Session["EmployeeList"];
        //var EmployeeList = Session["EmployeeList"] as List<Product>;
        //var EmployeeList = Session["EmployeeList"];

        GridView grid = new GridView();
        grid.DataSource = EmployeeList;

        grid.DataBind();

        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment; filename=Employees.xls");
        Response.ContentType = "application/ms-excel";

        Response.Charset = "";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        grid.RenderControl(htw);

        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();

        return RedirectToAction("Index");
    }
like image 33
Mari Avatar answered Oct 19 '25 01:10

Mari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!