zoukankan      html  css  js  c++  java
  • GridView 导出Excel

    前台:

     <td  style=" 150px;">
                                 <asp:Button ID="btnExcel" runat="server" Text="导出Excel/Export Excel" OnClick="btnExcel_Click" Width="100%" />
                            </td>

    后台:

            protected void btnExcel_Click(object sender, EventArgs e)
            {
                DateTime dt = System.DateTime.Now;
                string str = dt.ToString("yyyyMMddhhmmss");
                str = str + ".xls";
    
                gvDepartmentInfo.AllowPaging = false;
    
                gvDepartmentInfo.DataSource = GetData();
                gvDepartmentInfo.DataBind();
                GridViewToExcel(gvDepartmentInfo, "application/ms-excel", str);
    
                // Export(gvRecord, "application/ms-excel", str);
            }
    
            /// <summary>
            /// 将网格数据导出到Excel
            /// </summary>
            /// <param name="ctrl">网格名称(如GridView1)</param>
            /// <param name="FileType">要导出的文件类型(Excel:application/ms-excel)</param>
            /// <param name="FileName">要保存的文件名</param>
            public static void GridViewToExcel(Control ctrl, string FileType, string FileName)
            {
                HttpContext.Current.Response.Charset = "GB2312";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//注意编码
                HttpContext.Current.Response.AppendHeader("Content-Disposition",
                    "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
                HttpContext.Current.Response.ContentType = FileType;//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 
                ctrl.Page.EnableViewState = false;
                StringWriter tw = new StringWriter();
                HtmlTextWriter hw = new HtmlTextWriter(tw);
                ctrl.RenderControl(hw);
                HttpContext.Current.Response.Write(tw.ToString());
                HttpContext.Current.Response.End();
            }
            public override void VerifyRenderingInServerForm(Control control)
            {
    
            }
  • 相关阅读:
    Manage It! Part 2 规划和组织项目
    【转载】如何迅速成为Java高手
    Eclipse中最常用的快捷键
    向SQL Server全文索引进军,艰难历程
    数据库函数整理
    ASP.NET MVC简单编程篇(一)
    SQL Server存储过程及高级应用
    定义和赋值的区别 构造函数和拷贝构造函数
    SQL Server 2000
    Coustom web control 自定义控件
  • 原文地址:https://www.cnblogs.com/YoungPop-Chen/p/3402208.html
Copyright © 2011-2022 走看看