Excel 导出的方法 之二

 

 

// <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();
}

posted @ 2014-05-19 10:25  程序猿网友666  阅读(175)  评论(0编辑  收藏  举报