带分页功能的GridView导出Excel或Word的方法

时间:2022-04-21 14:45:54
#region 导出Excel按钮功能实现
    protected void BtnOutput_Click(object sender, EventArgs e)
    {
        Export("application/ms-excel", "盘点结果表.xls");//调用导出方法
    }
    #endregion

    #region 导出Excel方法
    private void Export(string FileType, string FileName)
    {
        //清楚分页
        GridView1.AllowPaging = false;
        GridView_BindByDate();
       
        Response.Clear();
        Response.Buffer = true;
        //设定输出的字符集
        Response.Charset = "GB2312";
       //解决导出到Excel2007乱码问题
        Response.Write("<meta http-equiv=Content-Type content=text/html;charset=GB2312>");

        //假定导出的文件名为盘点结果表.xls
        Response.AppendHeader("Content-Disposition", "attachment;filename=" +
                             HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
        //解决导出到Excel2007乱码问题
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

        //设置导出文件的格式
        Response.ContentType = FileType;
        //关闭ViewState
        this.EnableViewState = false;
        StringWriter stringWriter = new StringWriter();
        HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter);
        GridView1.RenderControl(textWriter);
        //把HTML写回浏览器
        Response.Write(stringWriter.ToString());
        Response.Flush();
        Response.End();
        GridView1.AllowPaging = true;//恢复分页
        //为GridView重新绑定数据源
        GridView_BindByDate();
      
    }

    #endregion

    #region 导出Word按钮功能实现
    protected void btnWord_Click(object sender, EventArgs e)
    {
        GridView1.AllowPaging = false;//清楚分页
        GridView_BindByDate();
        Response.Clear();
        Response.BufferOutput = true;
        //设定输出的字符集
        Response.Charset = "GB2312";
        //假定导出的文件名为FileName.doc
        Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.doc");
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        ////设置导出文件的格式
        Response.ContentType = "application/ms-word";
        //关闭ViewState
        this.EnableViewState = false;
        CultureInfo cultureInfo = new CultureInfo("ZH-CN", true);
        StringWriter stringWriter = new StringWriter(cultureInfo);
        HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter);
        GridView1.RenderControl(textWriter);
        ////把HTML写回浏览器
        Response.Write(stringWriter.ToString());
        Response.Flush();
        Response.End();
        //恢复分页
        GridView1.AllowPaging = true;
        //为GridView重新绑定数据源
        GridView_BindByDate();
    

    }
    #endregion

注:

#region 窗体标记
    //如果没有下面方法会报错,类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内(导出Excel或Word用)
    public override void VerifyRenderingInServerForm(Control control)
    {

    }
    #endregion