本文介绍了如何使用asp.net C#下载HTML表格到Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个HTML表这样:
I have an Html table as such:
<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();
}
任何想法?
推荐答案
所以我想通了两个解决方案,第一个是从我的网页重定向到一个通用处理器(发送字节流),并在处理程序做一些像user3851829建议以下
So I figured out two solutions, the first one is redirecting from my page to a generic handler (send the ByteStream) and in the handler do something like user3851829 suggested below
我所做的是类似的东西是什么,只是我从一个中继器的内容,然后渲染它放到StringBuilder这样:
What I did was something similar, only I took the content from a repeater and then rendered it into the stringBuilder as such:
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();
}
}
这两个答案都在!
这篇关于如何使用asp.net C#下载HTML表格到Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!