导出页面内容为Excel格式

//This is the Print code as below.
    protected void Button4_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "GB2312";
       Response.AddHeader("Content-Disposition", "attachment;   filename=" + System.Web.HttpUtility.UrlEncode("中文", System.Text.Encoding.UTF8) + ".xls");//这样的话,可以设置文件名为中文,且文件名不会乱码。其实就是将汉字转换成UTF8     

       // 如果设置为 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);
        Panel1.RenderControl(oHtmlTextWriter);//Add the Panel into the output Stream.
       //this.GridView1.RenderControl(oHtmlTextWriter);//将gridview输出,你也可以类似的写TextBox1.RenderControl...
        Response.Output.Write(oStringWriter.ToString());//Output the stream.
        Response.Flush();
        Response.End();
    }
    //End of the Print data code.
   
    //重载VerifyRenderingInServerForm方法,否则运行的时候会出现如下错误提示:“类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内
    public override void VerifyRenderingInServerForm(Control control)
    {
        //override VerifyRenderingInServerForm.
    }

原文地址:https://www.cnblogs.com/qxw0816/p/1563047.html