Search code examples
asp.net-mvcc#-4.0razorexport-to-excel

How to export mvc table data to excel?


I have View that contains some text box and dropdowns, Submit button and partial page. When i clicked on submit button, Partial page will load with data in table format.

Now i want a feature that, when i clicked on Export button the data in Partial page (Data contains in Table) should be exported to excel document.

I have Tried to do so by adding export submit button in partial page as below...

<input type="submit" value="Export" id="btnExport" />

In controller :

public ActionResult ExportToExcel()
{
Response.AddHeader("Content-Type", "application/vnd.ms-excel");
return View();
}

But its exporting All page details. i.e, Excel is showing all the textbox, dropdown, submit buttons, and table.

I just want table data. How do i get only table data. Please somebody help me with this..


Solution

  • You could place the table inside a partial and then render only the partial when exporting to Excel:

    public ActionResult ExportToExcel()
    {
        Response.AddHeader("Content-Type", "application/vnd.ms-excel");
        return PartialView("_Table");
    }