将web页面的GridView导出到excel文件,包括GridView中checkbox,image的处理。
public static void Export(Control control, string defaultFileName) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.BufferOutput = true; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + defaultFileName); HttpContext.Current.Response.ContentType = "application/ms-excel"; control.EnableViewState = false; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); System.IO.StringWriter stringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter textWriter = new System.Web.UI.HtmlTextWriter(stringWriter); control.RenderControl(textWriter); string result = stringWriter.ToString(); result = SpecialHandler(result); HttpContext.Current.Response.Write(string.Format(ExportToExcelHelper.BasicHTML, result)); HttpContext.Current.Response.End(); } private static string SpecialHandler(string result) { //把checkbox改成文字Yes/No result = Regex.Replace(result, "", "Received /", RegexOptions.IgnoreCase); result = Regex.Replace(result, " ", "Not received /", RegexOptions.IgnoreCase); result = result.Replace(" ", ""); //替换掉链接和外围的div result = Regex.Replace(result, " ", "", RegexOptions.IgnoreCase); result = Regex.Replace(result, " |||||\\n", "", RegexOptions.IgnoreCase); //TODO:处理图片,把图片替换成文字 string replaceText = string.Empty; Regex re = new Regex(" ", RegexOptions.None); //行标题特殊处理 Regex re2 = new Regex(" ", RegexOptions.None); return result; } public static string BasicHTML { get { return @" {0} "; } }