<form id="form1" runat="server"> 请选择数据库: <asp:RadioButtonList ID="RadioButtonList1" runat="server"> </asp:RadioButtonList> <asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Height="101px" Width="530px"></asp:TextBox> <asp:GridView ID="GridView1" runat="server" > </asp:GridView> </br> <asp:Button ID="Button1" runat="server" οnclick="Button1_Click" Text="Button" /> </form> using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; public partial class toexcel : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ListItem[] li={new ListItem("ca800_new","saf"),new ListItem("kehusql","saf")}; zj_static.Bind_Data_RBL(RadioButtonList1,li); // ScriptHelper.Alert(li.Length); } public override void VerifyRenderingInServerForm(Control control) { //这个函数要 } protected void Button1_Click(object sender, EventArgs e) { //string sqlstr = TextBox1.Text; //DataSet ds = DbHelper.Query("SELECT top 10 [AnnounceID], [UserName], [Topic], [Body], [DateAndTime], [isbest], [ip], [LastPost], [PostUserID] FROM [Dv_bbs]"); //GridView1.DataSource = ds; //GridView1.DataBind(); // TextBox1.Text = "SELECT top 10 [AnnounceID], [UserName], [Topic], [Body], [DateAndTime], [isbest], [ip], [LastPost], [PostUserID] FROM [Dv_bbs]"; if (TextBox1.Text.Trim().Equals("")) { //TextBox1.Text = "不能为空"; } string sqlstr = TextBox1.Text; try { DataSet ds = DbHelper.Query(sqlstr); GridView1.DataSource = ds; GridView1.DataBind(); } catch(Exception e1) { ScriptHelper.Alert("错误:" + e1.Message); return; } Response.Clear(); Response.Buffer = true; Response.Charset = "GB2312"; //下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开 //filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc .xls .txt .htm Response.AppendHeader("Content-Disposition", "attachment;filename=User_Data.xls"); Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //Response.ContentType指定文件类型 可以为application/ms-excel、application/ms-word、application/ms-txt、application/ms-html 或其他浏览器可直接支持文档 Response.ContentType = "application/ms-excel"; // 定义一个输入流 System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); GridView1.RenderControl(oHtmlTextWriter); //this 表示输出本页,你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件 Response.Write(oStringWriter.ToString()); Response.End(); } }