Hi nabilabolo,
Check this example. Now please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
NorthwindEntities entities = new NorthwindEntities();
return View(from customer in entities.Customers.Take(10)
select customer);
}
[HttpPost]
public FileResult Export()
{
NorthwindEntities entities = new NorthwindEntities();
var sbHtml = new System.Text.StringBuilder();
sbHtml.Append("<table><tr><td colspan='7' style='text-align: center; font-size:26px'><b>MONTHLY REPORT</b></td></tr></table><br/>");
sbHtml.Append("<table><tr><td colspan='7'><b>OVERALL SUMMARY</b></td></tr></table><br/><br/>");
sbHtml.Append("<table border='1'");
sbHtml.Append("<tr>");
sbHtml.Append("<td>CustomerId</td>");
sbHtml.Append("<td style='text-align:center'>Name</td>");
sbHtml.Append("<td style='text-align:center'>City</td>");
sbHtml.Append("<td style='text-align:center'>Country</td>");
sbHtml.Append("</tr>");
var customers = from customer in entities.Customers.Take(10)
select customer;
foreach (var customer in customers)
{
sbHtml.Append("<tr>");
sbHtml.Append("<td>" + customer.CustomerID + "</td>");
sbHtml.Append("<td>" + customer.ContactName + "</td>");
sbHtml.Append("<td>" + customer.City + "</td>");
sbHtml.Append("<td>" + customer.Country + "</td>");
sbHtml.Append("</tr>");
}
sbHtml.Append("</table>");
byte[] fileContents = System.Text.Encoding.Default.GetBytes(sbHtml.ToString());
return File(fileContents, "application/vnd.ms-excel", "Grid.xls");
}
}
View
@model IEnumerable<Export_Excel_MVC.Customer>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h4>Customers</h4>
<hr />
<table cellpadding="0" cellspacing="0">
<tr>
<th>CustomerID</th>
<th>ContactName</th>
<th>City</th>
<th>Country</th>
</tr>
@foreach (Customer customer in Model)
{
<tr>
<td>@customer.CustomerID</td>
<td>@customer.ContactName</td>
<td>@customer.City</td>
<td>@customer.Country</td>
</tr>
}
</table>
<br />
<br />
@using (Html.BeginForm("Export", "Home", FormMethod.Post))
{
<input type="submit" value="Export" />
}
</body>
</html>
Screenshot