Here I have created sample using aspx engine you can make use of razor engine,i hope this will help you out.
Index.aspx(View)
<div>
<table>
<tr>
<th>
</th>
<th>
Id
</th>
<th>
Name
</th>
<th>
Email
</th>
<th>
Contact
</th>
<th>
Address
</th>
<th>
City
</th>
<th>
State
</th>
<th>
Date
</th>
</tr>
<% foreach (var item in Model)
{ %>
<tr>
<td>
<%: item.Id %>
</td>
<td>
<%: item.Name %>
</td>
<td>
<%: item.Email %>
</td>
<td>
<%: item.Contact %>
</td>
<td>
<%: item.Address %>
</td>
<td>
<%: item.City %>
</td>
<td>
<%: item.State %>
</td>
<td>
<%: String.Format("{0:g}", item.Date) %>
</td>
</tr>
<% } %>
</table>
<p>
<%: Html.ActionLink("Download", "Download") %>
</p>
</div>
EmployeeController(Controller)
[HttpGet]
public ActionResult Index()
{
List<Employee> employees = new List<Employee>();
employees.AddRange(new Employee[] {
new Employee{
Id = 1,
Name="David",
Contact = 1222222,
Address ="Add1",
City ="Mumbai",
State = "Maharashtra",
Email = "David@gmial.com",
Date = DateTime.Parse("2015-02-02")
},
new Employee{
Id = 2,
Name="Kevin",
Contact = 1556555,
Address ="Add2",
City ="Mumbai",
State = "Maharashtra",
Email = "Kevin@gmial.com",
Date = DateTime.Parse("2015-05-02")
}
});
TempData["Data"] = employees;
return View(employees);
}
[HttpGet]
[ActionName("Download")]
public void Download()
{
List<Employee> emps = TempData["Data"] as List<Employee>;
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = emps;
grid.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.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();
TempData["Data"] = emps;
}
Employee
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Contact { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public DateTime Date { get; set; }
}
Screenshot
1)
2)