Monday, 17 December 2012

Export DataTable to Excel File in asp.net

Write the following code on which event you will require,

dt = city.GetAllCity();//your datatable 
string attachment = "attachment; filename=city.xls"; 
Response.ClearContent(); 
Response.AddHeader("content-disposition", attachment); 
Response.ContentType = "application/vnd.ms-excel"; 
string tab = ""; 
foreach (DataColumn dc in dt.Columns) 
{ 
    Response.Write(tab + dc.ColumnName); 
    tab = "\t"; 
} 
Response.Write("\n"); 
int i; 
foreach (DataRow dr in dt.Rows) 
{ 
    tab = ""; 
    for (i = 0; i < dt.Columns.Count; i++) 
    { 
        Response.Write(tab + dr[i].ToString()); 
        tab = "\t"; 
    } 
    Response.Write("\n"); 
} 
Response.End(); 

No comments:

Post a Comment