我有一个Html表:
<table cellpadding="0" cellspacing="0" border="0" class="Messages" id="idTbl" runat="server">
<tr>
<th>date</th>
<th>Subject</th>
</tr>
<tr class="myHot_smsMessages_new">
<td>01/01/2014</td>
<td>Some Subject No 1</td>
</tr>
<tr class="myHot_smsMessages_new">
<td>10/12/2013</td>
<td>Some subject no 2</td>
</tr>
</table>
并在服务器端:
protected void ExportToXLS(object sender, EventArgs e)
{
Response.ContentType = "application/x-msexcel";
Response.AddHeader("Content-Disposition", "attachment; filename=ExcelFile.xls"); Response.ContentEncoding = Encoding.UTF8;
StringWriter tw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(tw); idTbl.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}
有什么想法吗?
答案 0 :(得分:2)
static StringBuilder StrBuilder = new StringBuilder();
protected void lnkExcel_Clicked(object sender, EventArgs e)
{
//ExportGrid.ExportExcel(griditem);
ConfigureEmployeeExport();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/msexcel";
HttpContext.Current.Response.AddHeader("Content-Disposition", "filename=ExcelFile.xls");
HttpContext.Current.Response.Write(StrBuilder);
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
}
public void ConfigureEmployeeExport()
{
StrBuilder.Append("<table cellpadding='0' cellspacing='0' border='0' class='Messages' id='idTbl' runat='server'><tr><th>date</th><th>Subject</th></tr><tr class='myHot_smsMessages_new'><td>01/01/2014</td><td>Some Subject No 1</td></tr><tr class='myHot_smsMessages_new'><td>10/12/2013</td><td>Some subject no 2</td></tr></table>");
}
答案 1 :(得分:2)
所以我想出了两个解决方案,第一个是从我的页面重定向到通用处理程序(发送ByteStream),在处理程序中执行类似user3851829建议的解决方案
我所做的是类似的事情,只是我从转发器中取出内容,然后将其渲染到stringBuilder中:
protected void ExportToXLS(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Notifications.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter tw = new HtmlTextWriter(sw);
repeaterID.DataSource = Session["SomeDataFromSession"] as List<SomeObject>;
repeaterID.DataBind();
rptNotifications.RenderControl(tw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
这两个答案都有效!