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......
Thanks Mukesh, Your post is so helpful.
Is there anyway to change the color of the column names and can we put borders to the content in excel.
Glad to hear!
I didn’t try this but I will add a post soon about that after try this at my end.
I use this http://www.export2excel.net DLL. It is simple and very fast.
Thanks for sharing this….!