面朝大海,春暖华开

focus on scientific computue, 3dgis, spatial database
专注于科学计算、GIS空间分析

 

asp.net2.0 GridView 导出到 Excel

step 1:
在再这页的aspx文件<%@ Page Language="C#" AutoEventWireup="true"  %>
中加上EnableEventValidation="false"
step 2:
把这段代码加在cs 文件中
public override void VerifyRenderingInServerForm(Control control)
    {
        // base.VerifyRenderingInServerForm(control);
    }
step 3:
后台(1)
protected void btnExcel_Click(object sender, EventArgs e)
{
//导出到excel
GVStaff.AllowPaging = false;
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=人员信息.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 
this.EnableViewState = false;
System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
GV1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
后台(2)
    protected void Button1_Click(object sender, EventArgs e)
    {
        System.Web.UI.Control ctl = GridView1;
        bool CurrCtlVisible = ctl.Visible;
        ctl.Visible = true;
        Response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        Response.ContentType = "application/ms-excel";
        ctl.Page.EnableViewState = false;
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
        ctl.RenderControl(hw);
        Response.Write(tw.ToString());
        Response.End();

        ctl.Page.EnableViewState = true;
        ctl.Visible = CurrCtlVisible;
    }

posted on 2006-05-07 23:27  风过 无痕  阅读(350)  评论(0编辑  收藏  举报

导航

向日葵支付宝收钱码