closedxml is a .NET library for reading, manipulating and writing excel 2007+ (.xlsx, .xlsm) files. It aims to provide an intuitive and user-friendly interface to dealing with the underlying openxml API.
---Model Class ---
public class Employee
{
public int Id { get; set; }
public int FirstName { get; set; }
public int Department { get; set; }
}
---Controller ---
private SqlConnection con;
private SqlCommand cmd;
private voId connection()
{
con = new SqlConnection("Data Source=.;Integrated Security=true;Initial Catalog=TESTDB");
}
public ActionResult Index()
{
return View();
}
public List<Employee> GetData(int Id = 0)
{
List<Employee> emplst = new List<Employee>();
DataSet ds = new DataSet();
connection();
cmd = new SqlCommand("read_emp_rec", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Id", Id);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Employee empobj = new Employee();
empobj.Id = Convert.ToInt32(ds.Tables[0].Rows[i]["Id"].ToString());
empobj.FirstName = ds.Tables[0].Rows[i]["FirstName"].ToString();
empobj.Department = ds.Tables[0].Rows[i]["Department"].ToString();
emplst.Add(empobj);
}
con.Close();
return emplst;
}
public void ExportDataForEMPList(string FileName)
{
List<Employee> getemplst = GetData();
DataTable dt = ToDataTable(getemplst);
ExcelDownload(dt, FileName);
}
public DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//get all the properties by using reflection
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++)
{
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
public void ExcelDownload(DataTable dt, string FileName)
{
dt.TableName = FileName;
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
wb.Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename= " + FileName + ".xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
note : install nuget package ClosedXML
0 Comments
if you have any doubts , please let me know