Response.Buffer = true;
        //sExcelFileName = "方法.xls";
        HttpContext.Current.Response.Charset = "UTF-8";
        //HttpContext.Current.Response.Charset ="UTF-8";
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=方法.xls");
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        GridView1.Page.EnableViewState = false;
        System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);        System.IO.StringWriter tw = new System.IO.StringWriter(myCItrad);
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        GridView1.RenderControl(hw);           // 这里是红色显示,应该错误就在这里
        HttpContext.Current.Response.Write(tw.ToString());
        HttpContext.Current.Response.End(); 
运行出现如下错误:
只能在执行 Render() 的过程中调用 RegisterForEventValidation  谢谢!!!

解决方案 »

  1.   

    System.IO.StringWriter SW = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter HTW=new System.Web.UI.HtmlTextWriter(SW);
    DataGrid1.RenderControl(HTW);
    //Page为要导出的对象,当前是Page,如果是DataGrid,DataList等都可以
    Response.Buffer=true;
    Response.Clear();
    Response.ClearContent();
    Response.ClearHeaders();
    Response.ContentType =  "application/vnd.ms-excel";
    //Response.ContentType是输出流的 HTTP MIME 类型
    //Response.ContentType     --- word文件
    //application/vnd.ms-excel --- excel文件
    //...
    Response.Charset="utf-8";
    Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");
    Response.AddHeader("Content-Disposition", "attachment;filename=XXX.xls");
    //attachment --- 作为附件下载
    //inline --- 在线打开
    //filename如过是中文,则可以用HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8)
    //进行进行编码,以解决文件名乱码的问题
    Response.Write(SW.ToString());
    Response.Flush();
    Response.Close();
      

  2.   

    DataGrid1.RenderControl(HTW);这里错误啊!
      

  3.   

    看看这个,我以前写过的
    http://www.wsoft.net/Index/Catalog47/188.aspx
      

  4.   

    楼上的太复杂了吧?没法看啊!有具体简单的例子吗?能否借看呢?[email protected]  谢谢!