【C#】导出Excel

导出Excel的方法
1.利用web控件导出
        public static void OutputToExcel(string fileName,System.Web.UI.Control dg)
        {
            string str = fileName + ".xls";
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" +

HttpUtility.UrlPathEncode(str));
            HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("GB2312");
            HttpContext.Current.Response.Charset = "";
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            StringBuilder sb = new StringBuilder();
            StringWriter writer = new StringWriter(sb);
            HtmlTextWriter writer2 = new HtmlTextWriter(writer);
            dg.RenderControl(writer2);
            writer2.Close();
            writer.Close();
            HttpContext.Current.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel;

charset=gb2312\"/>");
            HttpContext.Current.Response.Write(sb.ToString());
            HttpContext.Current.Response.End();
        }
2.利用table字符串导出(与1基本差不多)
        public static void OutputToExcel(string fileName, string dtStr)
        {
            string str = fileName + ".xls";
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" +

HttpUtility.UrlPathEncode(str));
            HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("GB2312");
            HttpContext.Current.Response.Charset = "GB2312";
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            HttpContext.Current.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel;

charset=gb2312\"/>");
            HttpContext.Current.Response.Write(dtStr);
            HttpContext.Current.Response.End();
        }

posted @ 2014-03-19 09:28  酱油帝君  阅读(1146)  评论(0编辑  收藏  举报