想从Datalist中CheckBox选中的信息导出到Excel表中,怎么实现呢?大侠们,帮帮忙咯....
1 <form id="form1" runat="server">
2 <div>
3 <asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1">
4 <ItemTemplate>
5 <asp:CheckBox ID="CheckBox1" runat="server"/>
6 员工姓名:
7 <asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>'></asp:Label>
8 <asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>'></asp:Label>
9 </ItemTemplate>
10 </asp:DataList>
11 <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="导出Excel"/>
12 </div>
13 <asp:SqlDataSource ID="SqlDataSource1" runat="server"
14 ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
15 SelectCommand="SELECT [FirstName], [LastName] FROM [Employees]">
16 </asp:SqlDataSource>
17 </form>
我只在网上参考资料,能把全部的信息导出到Excel表中
这个是我自己找的一个解决方法,只是感觉太麻烦了,只能运用于一般的布局中
1 Response.Clear();
2 Response.BufferOutput = true;
3 Response.Charset = "gb2312";
4 Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
5 Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
6 Response.ContentType = "application/ms-excel";
7 DataList1.EnableViewState = false;
8
9 string str = "<table>";
10 for (int i = 0; i < DataList1.Items.Count; i++)
11 {
12 string lbString = String.Empty;
13 DataListItem dli = DataList1.Items[i];
14 //得到想要的数据
15 for (int k = 0; k < dli.Controls.Count; k++)
16 {
17 if (dli.Controls[k] is Label)
18 {
19 Label lb = dli.Controls[k] as Label;
20 lbString += lb.Text;
21 continue;
22 }
23 }
24
25 //判断是否需要输出到Excel
26 for (int j = 0; j < dli.Controls.Count; j++)
27 {
28 if (dli.Controls[j] is CheckBox)
29 {
30 CheckBox cb = dli.Controls[j] as CheckBox;
31 if (cb.Checked == true)
32 {
33 str += "<tr><td>"+ lbString +"</td></tr>";
34 }
35 }
36 }
37 }
38 str += "</table>";
39
40 System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("zh-CN", true);
41 System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
42 oStringWriter.WriteLine(str);
43 Response.Write(oStringWriter.ToString());
44 Response.End();
你既然能把全部的信息导出到Excel表中,那么把选中的信息导入到excel是一样的啊,只是数据量不同罢了,获取datalist选中项:http://social.msdn.microsoft.com/Forums/zh-CN/295/thread/f64d5aa6-0368-402e-bafd-0ecfe47d2c2b/
你可以用NPOI,见我的首页,有教程
看到最多的答案是关于DataTable的操作,但这个DataList的数据不是DataTable的,所以就像办法向DataTable转换了....嘿嘿