Export data to excel using c#

In web site development sometime we need to export our data to excel for re-use same data at another place or for backup purpose.

In this post I am going to explain how do we simply export our website data to excel. In the below code, I am pasing static data values to datatable, but you can customize the code as per your requirement.

Simple code to export datatable to excel using c#

 DataTable dataTable = new DataTable();
 dataTable.Columns.Add("Id");
 dataTable.Columns.Add("Name");
 dataTable.Columns.Add("Website");
 dataTable.Rows.Add("1", "mukesh","learnsharecorner.com");
 dataTable.Rows.Add("2", "ramesh", "learnsharecorner.com");
 string fileName = "excelfile";
 var response = HttpContext.Current.Response;
 string attachment = "attachment; filename=" + fileName + ".xls";
 response.ClearContent();
 response.AddHeader("content-disposition", attachment);
 response.ContentType = "application/vnd.ms-excel";
 string tab = "";
 foreach (DataColumn dc in dataTable.Columns)
 {
 response.Write(tab + dc.ColumnName);
 tab = "\t";
 }
 response.Write("\n");
 int i;
 foreach (DataRow dr in dataTable.Rows)
 {
 tab = "";
 for (i = 0; i < dataTable.Columns.Count; i++)
 {
 response.Write(tab + dr[i]);
 tab = "\t";
 }
 response.Write("\n");
 }
 response.End();

This is simplest way to implement the code in asp.net application using c#. If you unable to do this and face any problem then please hire me.

I will solve the problem asap.

Happy coding......

Posted by | View Post | View Group