GridView数据导出到Excel中


将GridView中数据导出到Excel中


protected   void  Page_Load( object  sender, EventArgs e)
    
{
        
if (!Page.IsPostBack)
        
{
            BindData();
        }

    }

    
    
private   void  BindData()
    
{
        
string query = "SELECT * FROM orders";
        SqlConnection conn 
= new SqlConnection("server=.;database=northwind;uid=sa;pwd=sa");
        SqlDataAdapter ad 
= new SqlDataAdapter(query, conn);
        DataSet ds 
= new DataSet();
        ad.Fill(ds);
        GridView1.DataSource 
= ds.Tables[0];
        GridView1.DataBind();

    }



    
public   override   void  VerifyRenderingInServerForm(Control control)
    
{

        
    }


    
protected   void  Button2_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);


        GridView1.AllowPaging 
= false;
        BindData();
        GridView1.RenderControl(htmlWrite);

        Response.Write(stringWrite.ToString());

        Response.End();

        GridView1.AllowPaging 
= true;
        BindData();

    }

导出成功!
注意如果数据源是NorthWind中的Products表(原因不清楚,应该还有其他的数据源也会出现这种情况)
会出现异常
只能在执行 Render() 的过程中调用 RegisterForEventValidation;


有两种方法可以解决这个问题:
1.修改web.config(不推荐) <pages enableEventValidation ="false" ></pages>
2.直接在导出Execl的页面修改
<% @ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true"

 CodeFile
="ExportGridView.aspx.cs" Inherits="ExportGridView" 
%>


 

你可能感兴趣的:(GridView)