asp.net中datagrid导出excel

public partial class _Default : System.Web.UI.Page
{
    SqlConnection sqlcon = new SqlConnection(ConfigurationManager.AppSettings["conStr"]);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Export("application/ms-excel", "商品信息表.xls");
    }
    private void Export(string FileType, string FileName)
    {
        Response.Charset = "GB2312";
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        this.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        GridView1.RenderControl(hw);
        Response.Write(tw.ToString());
        Response.End();
    }
    private void bind()
    {
        SqlDataAdapter myda = new SqlDataAdapter("select * from tb_GoodsInfo", sqlcon);
        DataSet myds = new DataSet();
        sqlcon.Open();
        myda.Fill(myds);
        sqlcon.Close();
        GridView1.DataSource = myds;
        GridView1.DataBind();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
       /* if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:¥#,###.00");
        }*/
    }

}


只能在执行Render() 的过程中调用 RegisterForEventValidation;

在实现"将GridView中的数据导出到Excel中"的时候出现了如下错误:
用户代码未处理 InvalidOperationException
只能在执行 Render() 的过程中调用 RegisterForEventValidation;
         EnableEventValidation属性是 .NET Framework 2.0 中是新增的属性,默认的情况下该属性的值为true;通过这个新增的功能ASP.NET会检查 POST方法中的所带的参数,如果认为不合法,就会抛出异常。这个设计的目的是为了防止恶意用户利用post 方法发送一些恶意数据,但是有时也会出现类似上面的错误。
只要禁止这个功能,问题就能得到解决。可以通过以下两种途径解决:
1、在Web.Config文件中:在<system.web></system.web>标记中添加如下代码:
<system.web>
            <pages enableEventValidation="false"> </pages>
</system.web>
2、在具体的.aspx页面的源代码中修改代码,如下:
<%@ Page Language="C#"  EnableEventValidation="false" CodeFile="GridView_Export_Excel.aspx.cs" Inherits="GridView_Export_Excel" %>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值