asp.net 导出Excel

.Net 导出到Excel的方法有很多,园子里相关的文章和代码也很多,在本文中我只讲解两种

一、导出整张页面到Excel

public static void DownloadExcel(this Page thispage)

{

            HttpContext.Current.Response.Clear();

            HttpContext.Current.Response.Buffer = true;

            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMdd") + ".xls");

            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;

            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

            System.IO.Stream stream= HttpContext.Current.Response.OutputStream;

            

            thispage.EnableViewState = false;  

}

二、将指定的某个用户控件中的数据导出到Excel

public static void DGToExcel(System.Web.UI.Control ctl, string homeTeamName, string awayTeamName)

        {

            ctl.Page.EnableViewState = true;

            //文件名称(可以自定义)
string filename = HttpUtility.UrlEncode(homeTeamName) + "VS" + HttpUtility.UrlEncode(awayTeamName) + DateTime.Now.ToString("yyyyMMdd") + ".xls"; System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); ctl.RenderControl(hw); //在这里对html标签中的一些不需要的字符进行过滤(可以自由发挥)
string htmlText = tw.ToString(); htmlText = Regex.Replace(htmlText, @"<th", @"<th bgcolor=""#FF0000""", RegexOptions.Compiled); htmlText = Regex.Replace(htmlText, @"<td", @"<td align=""center""", RegexOptions.Compiled); byte[] buffer = Encoding.Default.GetBytes(htmlText); MemoryStream ms = new MemoryStream(buffer); long fileSize = ms.Length; HttpContext.Current.Response.ContentType = "application/ms-excel";//application/octet-stream HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\";");//attachment --- 作为附件下载 ////inline --- 在线打开 HttpContext.Current.Response.AddHeader("Content-Length", fileSize.ToString()); byte[] fileBuffer = new byte[fileSize]; ms.Read(fileBuffer, 0, (int)fileSize); HttpContext.Current.Response.BinaryWrite(fileBuffer); ms.Close(); HttpContext.Current.Response.End(); tw.Dispose(); tw.Flush(); }

 

你可能感兴趣的:(asp.net)