Hi nabilabolo,
Check this example. Now please take its reference and correct your code.
For this exampe i have used ClosedXML to export to excel. Refer below link for more details.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Namespaces
using System.Data;
using System.IO;
using System.Linq;
using ClosedXML.Excel;
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
string customerId = "ALFKI";
List<OrderModel> orders = new List<OrderModel>();
CustomerModel customer = new CustomerModel();
using (NorthwindEntities db = new NorthwindEntities())
{
orders = (from o in db.Orders
join c in db.Customers
on o.CustomerID equals c.CustomerID
where o.CustomerID == customerId
select new OrderModel
{
OrderID = o.OrderID,
OrderDate = o.OrderDate,
Freight = o.Freight
}).ToList();
customer = db.Customers.Where(x => x.CustomerID == customerId)
.Select(c => new CustomerModel
{
CustomerID = c.CustomerID,
Name = c.ContactName,
Address = c.Address
}).FirstOrDefault();
}
DataTable dt = ToDataTable(orders);
using (XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add("OrderDetail");
var aCode = 65;
var wsReport1 = ws.Range(string.Format("A{0}:{1}{0}", 1, Char.ConvertFromUtf32(aCode + dt.Columns.Count - 1)));
wsReport1.Merge();
wsReport1.Style.Border.OutsideBorder = XLBorderStyleValues.None;
wsReport1.Value = string.Format("ID : {0}", customer.CustomerID);
var wsReport2 = ws.Range(string.Format("A{0}:{1}{0}", 2, Char.ConvertFromUtf32(aCode + dt.Columns.Count - 1)));
wsReport2.Merge();
wsReport2.Style.Border.OutsideBorder = XLBorderStyleValues.None;
wsReport2.Value = string.Format("Name : {0}", customer.Name);
var wsReport3 = ws.Range(string.Format("A{0}:{1}{0}", 3, Char.ConvertFromUtf32(aCode + dt.Columns.Count - 1)));
wsReport3.Merge();
wsReport3.Style.Border.OutsideBorder = XLBorderStyleValues.None;
wsReport3.Value = string.Format("Address : {0}", customer.Address);
ws.Row(3).InsertRowsBelow(1);
ws.Row(4).Style.Border.OutsideBorder = XLBorderStyleValues.None;
ws.Row(4).Style.Border.RightBorder = XLBorderStyleValues.None;
ws.Row(4).Style.Border.LeftBorder = XLBorderStyleValues.None;
int rowIndex = 5;
int columnIndex = 0;
foreach (DataColumn column in dt.Columns)
{
ws.Cell(string.Format("{0}{1}", Char.ConvertFromUtf32(aCode + columnIndex), rowIndex)).Value = column.ColumnName;
ws.Cell(string.Format("{0}{1}", Char.ConvertFromUtf32(aCode + columnIndex), rowIndex)).Style.Border.OutsideBorder = XLBorderStyleValues.None;
ws.Cell(string.Format("{0}{1}", Char.ConvertFromUtf32(aCode + columnIndex), rowIndex)).Style.Font.Bold = true;
columnIndex++;
}
rowIndex++;
foreach (DataRow row in dt.Rows)
{
int valueCount = 0;
foreach (object rowValue in row.ItemArray)
{
ws.Cell(string.Format("{0}{1}", Char.ConvertFromUtf32(aCode + valueCount), rowIndex)).Value = rowValue;
ws.Cell(string.Format("{0}{1}", Char.ConvertFromUtf32(aCode + valueCount), rowIndex)).Style.Border.OutsideBorder = XLBorderStyleValues.None;
valueCount++;
}
rowIndex++;
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=CustomerOrders.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
return View();
}
public DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
}
Screenshot