GridView数据导出到Excel、Word

 将GridView数据导出到Excel、Word。

需注意:

1)要写一个空的VerifyRenderingInServerForm方法(必须写),以确认在运行时为指定的ASP.NET 服务器控件呈现HtmlForm 控件;

2)修改你的aspx文件中的:

<%@ Page EnableEventValidation="false" %>

代码如下:

    protected void Button1_Click(object sender, EventArgs e)
    
{
        GridView1.AllowPaging 
= false;
        GridView1.AllowSorting 
= false;
        GridView1.DataBind();
        Export(
"application/ms-excel""visitrecord.xls");        
        
//Export("application/ms-word", "visitrecord.doc");
        
//Export("application/text/html", "visitrecord.html");
        GridView1.AllowPaging = true;
        GridView1.AllowSorting 
= true;        
    }


    
private void Export(string FileType, string FileName)
    
{
        Response.Clear();
        Response.Buffer 
= true;
        Response.Charset 
= "GB2312";
        Response.ContentEncoding 
= System.Text.Encoding.UTF8;
        Response.AppendHeader(
"Content-Disposition""attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
        Response.ContentType 
= FileType;
        
this.EnableViewState = false;
        StringWriter sw 
= new StringWriter();
        HtmlTextWriter hw 
= new HtmlTextWriter(sw);
        GridView1.RenderControl(hw);
        Response.Write(sw.ToString());
        Response.End();
    }


    
public override void VerifyRenderingInServerForm(Control control)
    
{
        
//base.VerifyRenderingInServerForm(control);
    }

 

posted @ 2008-07-27 11:58  轻嬴巧凤  阅读(371)  评论(2编辑  收藏  举报