Hi varun.p,
Check this example. Now please take its reference and correct your code.
Refering below article i have created the example.
ClosedXML MVC Example: Export to Excel using ClosedXML in ASP.Net MVC
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Download and install 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(string[] selectedCustomers)
{
NorthwindEntities entities = new NorthwindEntities();
DataTable dt = new DataTable("Grid");
dt.Columns.AddRange(new DataColumn[4] { new DataColumn("CustomerId"),
new DataColumn("ContactName"),
new DataColumn("City"),
new DataColumn("Country") });
var customers = from customer in entities.Customers.Take(10)
select customer;
foreach (var customer in customers)
{
if (selectedCustomers.Contains(customer.CustomerID))
{
dt.Rows.Add(customer.CustomerID, customer.ContactName, customer.City, customer.Country);
}
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
using (MemoryStream stream = new MemoryStream())
{
wb.SaveAs(stream);
return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Grid.xlsx");
}
}
}
}
View
@model IEnumerable<Export_Checked_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 />
@using (Html.BeginForm("Export", "Home", FormMethod.Post))
{
<table cellpadding="0" cellspacing="0">
<tr>
<th></th>
<th>CustomerID</th>
<th>ContactName</th>
<th>City</th>
<th>Country</th>
</tr>
@foreach (Customer customer in Model)
{
<tr>
<td><input type="checkbox" name="selectedCustomers" value="@customer.CustomerID" /></td>
<td>@customer.CustomerID</td>
<td>@customer.ContactName</td>
<td>@customer.City</td>
<td>@customer.Country</td>
</tr>
}
</table>
<br />
<br />
<input type="submit" value="Export" />
}
</body>
</html>
Screenshot