Friday, January 13, 2017

How to generate excel using data table in c#

Public void GenerateExcel(Datatable dt)
{
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