将GridView中的数据导出为Excel

  将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。在输出前把分页禁用,绑定所有数据后输出,完成后在重新启用分页就好了。

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

转载于:https://www.cnblogs.com/yxbsmx/articles/1339681.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值