Export to excel using MVC 4

In this article I will show you how to export student detail from MVC 4 application using Entity-framework. Let start with creating simple MVC 4 project.

1. Open Visual Studio 2010 => New Project => Select ASP.Net MVC4 web Application => Name it Export => Click ok

1

1

2. Select Internet Application click OK.

2

2

3. Now add 2 class file name ExportDB and StudenDetail respectively and add code mention below


public class Export_Excel: DbContext
{
public DbSet<StudentDetail> Studentrecord{ get; set; }
}

public class StudentDetail
{
[Key]
public int id { get; set; }
[Required]
public String Name { get; set; }
public String Address { get; set; }
public String Marks { get; set; }
}

4. Now add right click on controller => Add => Controller.
5. Put controller name “StudentDetail”, model class StudentDetail and data context class “Export_Excel” then click on Add button. It will create one controller file and 5 cshtml file for add/edit/delete.

3

3

6. Run application by F5 and in your URL type studentdetail if cause error then type studentdetail/create otherwise click on create new. Add data from here.

4

4

5

5

7. After adding records from application. Add following code in studentdetailcontroller

public ActionResult ExportData()
 {
 GridView gv = new GridView();
 gv.DataSource = db.Studentrecord.ToList();
 gv.DataBind();
 Response.ClearContent();
 Response.Buffer = true;
 Response.AddHeader("content-disposition", "attachment; filename=Marklist.xls");
 Response.ContentType = "application/ms-excel";
 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("StudentDetails");
 }

8. Add following code in index.cshtml

@using (Html.BeginForm("ExportData", "Studentdetail", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td></td>
<td>
<input type="submit" name="Export" id="Export" value="Export" /></td>
</tr>
</table>
}

9. Now run application and append studentdetail on URL and click on export button.

6

6

This will export you data into excel. For code check this: click

10 thoughts on “Export to excel using MVC 4

  1. Pingback: Export to word using MVC 4 | Satish Ratnaparkhi's blog
  2. Thank you So Much SATISHRATNAPARKHI, it’s worked excelent.
    but I have a situation, i have a search option, and when I try to export the result, it’s bringing all the data, not my search result.

    How can i do that

    thank you in Advance

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.