//重写此方法,否则会出现类型"GridView"的控件"GridView1"必须放在具有runat=server的窗体标记内."的错误.
public override void VerifyRenderingInServerForm(Control control)
{
}
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=.;database=northwind;uid=sa;pwd=");
SqlDataAdapter da = new SqlDataAdapter("select * from customers", con);
DataSet ds = new DataSet();
da.Fill(ds);
this.GridView1.DataSource = ds;
this.GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.doc");
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ContentType = "application/ms-word";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.GridView1.RenderControl(oHtmlTextWriter);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
}
导入到EXCEL与之类似:
以下是引用片段:
-----
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.GridView1.RenderControl(oHtmlTextWriter);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();