C# 将GridView导出为Excel注意事项

来源:互联网 发布:mac系统qq远程 编辑:程序博客网 时间:2024/05/18 01:55

将GridView中的数据导出为Excel,然后由用户选择是保存还是打开打印,虽然代码比较简单。

无非就是用IO流去写成为Excel,但是有很多细节稍不注意就为成为困扰。

  还是写下来,以后碰到了来查查。

     先贴个源码:

 

   public override void VerifyRenderingInServerForm(Control control)
    { }

    protected void Print_ServerClick(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "GB2312";
        string filename = "attachment;filename=" + System.Web.HttpUtility.UrlEncode( this.DropDownList1.SelectedItem.Text + "年" + this.DropDownList2.SelectedItem.Text + "月技术交易奖酬金",System.Text.Encoding.UTF8)+".xls";
        Response.AppendHeader("Content-Disposition", filename);
        // 如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码!!!
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
        this.GVStart.AllowPaging = false;
        BindGridView();

        this.GVStart.RenderControl(oHtmlTextWriter);
        Response.Output.Write(oStringWriter.ToString());
        Response.Flush();
        Response.End();

        this.GVStart.AllowPaging = true;
        this.GVStart.PageIndex = 0;
        BindGridView();

    }

     1:首先在打印页面的HTML<%@ Page />标签中加入 EnableEventValidation = "false",否则可能会出现

错误:只能在执行 Render() 的过程中调用 RegisterForEventValidation

     2:重写方法  public override void VerifyRenderingInServerForm(Control control) ,否则会出现,GridView控件

必须出现在 RunAt="server" 标签中,原因嘛,就不在此啰嗦了。
     3:文件名中文乱码,很简单用 System.Web.HttpUtility.UrlEncode转换一下为UTF8就好了。

     4:至于分页的GridView。在输出前把分页禁用,绑定所有数据后输出,完成后在重新启用分页就好了。

     至于还有其它的就照着上面的代码写没有其它了...

原创粉丝点击