ASP.ENT c# 将数据导出为Excel

来源:互联网 发布:java学生管理系统项目 编辑:程序博客网 时间:2024/06/05 15:11
       
public void ToExcel(DataTable dt,HttpContext content)        {            string filename = DateTime.Now.ToString("yyyyMMddHHmmss");            content.Response.Clear();            string fileName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(filename));            content.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");            content.Response.ContentType = "applicationnd.ms-excel";            content.Response.Charset = "utf-8";            StringBuilder s = new StringBuilder();            s.Append("<HTML><HEAD><TITLE>" + fileName + "</TITLE><META http-equiv=\"Content-Type\" content=\"textml; charset=utf-8\"></head><body>");            System.IO.StringWriter sw = new System.IO.StringWriter();            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);            System.Web.UI.WebControls.GridView dg = new System.Web.UI.WebControls.GridView();            dg.DataSource = dt;            dg.DataBind();            dg.RenderControl(htw);            content.Response.Write(sw.ToString());            content.Response.End();        }