public void Create_Save_Download_Excel()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Col1", typeof(string)),
new DataColumn("Col2", typeof(string)),
new DataColumn("Col3",typeof(string))});
dt.Rows.Add("1", "TestA", "A");
dt.Rows.Add("2", "TestB", "B");
dt.Rows.Add("3", "TestB", "C");
dt.Rows.Add("4", "TestB", "D");
StringBuilder sb = new StringBuilder();
sb.Append("<html >");
sb.Append("<head>");
sb.Append("</head>");
sb.Append("<body>");
sb.Append("<table border='1px' cellpadding='1' cellspacing='1'
bgcolor='lightyellow' style='font-family:Arial; font-size:large'>");
sb.Append("<tr >");
foreach (DataColumn myColumn in dt.Columns)
{
sb.Append("<td >");
sb.Append(myColumn.ColumnName);
sb.Append("</td>");
}
sb.Append("</tr>");
foreach (DataRow myRow in dt.Rows)
{
sb.Append("<tr >");
foreach (DataColumn myColumn in dt.Columns)
{
sb.Append("<td >");
sb.Append(myRow[myColumn.ColumnName].ToString());
sb.Append("</td>");
}
sb.Append("</tr>");
}
//Close
tags.
sb.Append("</table>");
sb.Append("</body>");
sb.Append("</html>");
string Htmltext = sb.ToString();
string CopyTxt = Htmltext;
//////////////////
Save Data on specific location
string filePath = Server.MapPath("~/Import/");
if (!System.IO.Directory.Exists(filePath))
{
System.IO.Directory.CreateDirectory(filePath);
}
string fileName = "Jaiho_"+System.DateTime.Now.ToString("yyyyMMddhhmmss")+".xls";
System.IO.File.WriteAllText(filePath +
fileName, CopyTxt);
//////////////////
Download data
try
{
string strcontentType = "application/excel";
Response.ClearContent();
Response.ClearHeaders();
Response.BufferOutput = true;
Response.ContentType =
strcontentType;
Response.AddHeader("Content-Disposition", "attachment; filename=" +
fileName);
Response.Write(Htmltext.ToString());
Response.Flush();
//
Response.Close();
//
Response.End();
}
catch (Exception ex)
{
string msg = ex.Message;
}
}