string html = RenderControl(this.Page);//获取控件最终呈现的HTML,最好是Table MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(html)); System.IO.MemoryStream ms = stream; byte[] bt = ms.ToArray(); //客户端保存的文件名 //以字符流的形式下载文件 string file = $"output.xls"; System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file); System.Web.HttpContext.Current.Response.OutputStream.Write(bt, 0, bt.Length); this.Response.Flush(); this.Response.End();
public static string RenderControl(Control control) {StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);control.RenderControl(htmlTextWriter);htmlTextWriter.Flush();htmlTextWriter.Close();return stringWriter.ToString(); }
<table id="tb" style="border-collapse: collapse; width: 100%; line-height: 30px;border:1px solid black;border-color:#000;width:1200px;" ><%--bordercolor="#000000" cellspacing="0" width="300" align="center" bgcolor="#ffffff" border="1"--%><tr><th colspan="<%= dthxry.Rows.Count+8 %>" style="font-size: 20px; height: 60px;border:1px solid black;"><h1><%= sjnf %> 年 <%= jd %> 季度 社区正职/部门正职班子评价得分</h1></th></tr><tr><th rowspan="2" style="<%= css%>">社区</th><th rowspan="2" style="<%= css%>">姓名</th><th rowspan="2" style="<%= css%>">社区包联领导</th><th rowspan="2" style="<%= css%>">包联领导评分(40%)</th><th colspan="<%= dthxry.Rows.Count+2 %>" style="<%= css%>">班子评分(20%)</th><th rowspan="2" style="<%= css%>">线下分(40%)</th><th rowspan="2" style="<%= css%>">综合得分</th></tr><tr><%foreach (System.Data.DataRow r in dthxry.Rows){ %><th style="<%= css%>"><%= r["username"] %></th><%} %><th style="<%= css%>">班子总分</th><th style="<%= css%>">班子平均分(20%)</th></tr><tbody><% foreach (System.Data.DataRow r in dtData.Rows){ %><tr><th style="<%= css%>"><%=r["deptname"] %></th><th style="<%= css%>"><%=r["username"] %></th><th style="<%= css%>">社区包联领导</th><th style="<%= css%>"><%=r["blldpf"] %></th><% foreach (string s in cols){ %><th style="<%= css%>"><%=r[s] %></th><%} %><th style="<%= css%>"><%= ((decimal)r["bzzf"]).ToString("0.##") %></th><th style="<%= css%>"><%=((decimal)r["bzpjf"]).ToString("0.##") %></th><th style="<%= css%>"><%=((decimal)r["xxf"]).ToString("0.##") %></th><th style="<%= css%>"><%=((decimal)r["zhdf"]).ToString("0.##") %></th></tr><%} %></tbody> </table>