请帮助我将数据从asp.net c#中的datalist网页导出到excel表,我想将每条记录导出到单独的表中。注意:我在 datalist 中使用了 Item 模板,如下图所示
问问题
834 次
1 回答
0
试试这个例子:
<form id="form1" runat="server">
<div>
<asp:DataList ID="dlstudent" runat="server" DataKeyField="STUDENT_ID"
DataSourceID="SqlDataSource1">
<HeaderStyle Font-Bold="True" BorderColor="Black" />
<HeaderTemplate>
<table border="1"><tr style="background-color:Blue;color:White;">
<td><b>Student Name</b> </td>
<td>Student Address</td>
<td>Student Class</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr style="font-style:italic;">
<td align="center"><asp:Label ID="lblname" runat="server"
Text='<%# Eval("STUDENT_NAME") %>'></asp:Label></td>
<td align="center"><asp:Label ID="lbladdress" runat="server"
Text='<%# Eval("STUDENT_ADDRESS") %>'></asp:Label></td>
<td align="center"><asp:Label ID="lblclass" runat="server"
Text='<%# Eval("STUDENT_CLASS") %>'></asp:Label></td>
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TestBlogConnectionString %>"
SelectCommand="SELECT * FROM [STUDENT_DETAIL]"></asp:SqlDataSource>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Export To Excel" />
</div>
</form>
背后的代码
protected void Button1_Click(object sender, EventArgs e)
{
try
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "StudentDetail.xls"));
Response.ContentType = "application/ms-excel";
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter writer = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter html = new System.Web.UI.HtmlTextWriter(writer);
dlstudent.DataBind();
dlstudent.RenderControl(html);
Response.Write(writer.ToString());
Response.Flush();
Response.End();
}
catch (Exception ex)
{
}
}
参考:http ://www.aspmantra.com/2013/07/how-to-export-datalist-data-to-excel.html
于 2017-07-03T11:22:13.103 回答