How to Export DataTable to Excel using c#
As you know Export data as Excel file in C# is one of the most used functionality in the applications. So here, I am going to sharing how to Export data as Excel using C#.
Following is simple c# code that export data as Excel
public void ExportToExcel()
YOU MAY ALSO LIKE...
Export data as Excel file in C#
Export data as PDF file in C#
Export data as CSV file in C#
Export data as Word file in C#
I hope you are enjoying with this post! Please share with you friends!! Thank you!!!
As you know Export data as Excel file in C# is one of the most used functionality in the applications. So here, I am going to sharing how to Export data as Excel using C#.
Following is simple c# code that export data as Excel
public void ExportToExcel()
{
//Fetching user
records with GetUserDetails method.
/// Here you
can write your own code to fetch recodes as per you DB connections.
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("ID", typeof(long)),
new DataColumn("Name", typeof(string)),
new DataColumn("Age", typeof(int)),
new DataColumn("Address", typeof(string)),
new DataColumn("DOB", typeof(string)),
});
foreach (var x in UserList)
{
dt.Rows.Add(x.ID, x.Name,
x.Age, x.Address, x.DOB);
}
GridView GridView1
= new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=User.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i
< GridView1.Rows.Count; i++)
{
//adding class text
style to each Row
GridView1.Rows[i].Attributes.Add("class", "rowcss");
}
GridView1.RenderControl(hw);
//Apply style to
format numbers to string
string style = @"<style>.rowcss
{ mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
YOU MAY ALSO LIKE...
Export data as Excel file in C#
Export data as PDF file in C#
Export data as CSV file in C#
Export data as Word file in C#
I hope you are enjoying with this post! Please share with you friends!! Thank you!!!
I enjoy the efforts you have put in this, regards for all the great content . help with excel spreadsheet
ReplyDelete