// <summary>
/// 导出到Excel lichenghu
///
</summary>
/// <param name="dt"></param>
public static void ToExcel(DataTable dt)
{
string sb =
"";
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
sb = sb + dr[i].ToString() + "\t";
}
sb = sb + "\n";
}
HttpContext.Current.Response.AppendHeader("Content-Disposition",
"attachment;filename=MyExcel.xls");
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType =
"application/ms-excel";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new
System.Web.UI.HtmlTextWriter(tw);
hw.WriteLine(sb.ToString());
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
hw.Flush();
hw.Close();
tw.Flush();
tw.Close();
}
原文:http://www.cnblogs.com/chenghu/p/3736330.html