VS2005中将GridView 中的数据导出至excel

1、先在页面中添加一个按钮:
<asp:LinkButton ID="libExcel" runat="server" OnClick="libExcel_Click" >导出Excel</asp:LinkButton>
2、为Gridview绑定数据:
public void BindExpertsData()
    {
        CExpertsInfoCollection xList = cExpertsInfo.Search();

        grdvList.DataKeyNames = new string[] { "ID", "ExpertName" };
        grdvList.DataSource = xList;
        grdvList.DataBind();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindExpertsData();
        }
    }
3、导出数据。在libExcel的单击事件中来完成导出。
protected void libExcel_Click(object sender, EventArgs e)
    {

        Response.Clear();

        Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
        Response.Charset = "gb2312";
        Response.ContentType = "application/vnd.xls";

        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        grdvList.AllowPaging = false;//导出前先取消分页,以便能将所有数据导出。
        BindExpertsData();//再重新绑定一次数据

        grdvList.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();

        grdvList.AllowPaging = true;//导出后先取消分页,以便能将所有数据导出。
        BindExpertsData();//再重新绑定一次数据
    }
4、重写一个空的VerifyRenderingInServerForm方法。
public override void VerifyRenderingInServerForm(Control control)
    {

            /*以确认在运行时为指定的ASP.NET 控件呈现HtmlForm 控件*/
    }

5、在页面的page属性中加入EnableEventValidation = "false" .如:
<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation = "false" CodeFile="ExpertsList.aspx.cs" Inherits="ExpertsList" %>
6、注意。
若在GridView中定义了按钮列,在导出可能需要将它隐藏。

posted @ 2009-07-24 12:42  xumingming  阅读(648)  评论(2编辑  收藏  举报