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

    private void toexcel(string title)
        {
                    Response.Clear();
            Response.Buffer = false;
            Response.Charset = "utf-8";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(title) + ".xls");
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "application/ms-excel";
            Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
            this.EnableViewState = false;
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
            GridView1.RenderControl(oHtmlTextWriter);// 数字字符导Excel后转Text格式,否则前面的 0 字符会自动舍弃

            Response.Write(AddExcelHead());
            Response.Write(oStringWriter.ToString());
            Response.Write(AddExcelbottom());
            Response.End();
        }
       
        protected void btn_toexcel_Click(object sender, EventArgs e)
        {
            toexcel("订单详细");
        }
        public static string AddExcelHead()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
            sb.Append(" <head>");
            sb.Append(" <!--[if gte mso 9]><xml>");
            sb.Append("<x:ExcelWorkbook>");
            sb.Append("<x:ExcelWorksheets>");
            sb.Append("<x:ExcelWorksheet>");
            sb.Append("<x:Name></x:Name>");
            sb.Append("<x:WorksheetOptions>");
            sb.Append("<x:Print>");
            sb.Append("<x:ValidPrinterInfo />");
            sb.Append(" </x:Print>");
            sb.Append("</x:WorksheetOptions>");
            sb.Append("</x:ExcelWorksheet>");
            sb.Append("</x:ExcelWorksheets>");
            sb.Append("</x:ExcelWorkbook>");
            sb.Append("</xml>");
            sb.Append("<![endif]-->");
            sb.Append(" </head>");
            sb.Append("<body>");
            return sb.ToString();
        }
        public static string AddExcelbottom()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("</body>");
            sb.Append("</html>");
            return sb.ToString();
        }

    //重新下面方法解决错误:类型GridView的控件GridView1必须放置在具有runat=server的窗体标记内 

        public override void VerifyRenderingInServerForm(Control control)
        {

        } 

  • 相关阅读:
    客商支付明细SQL_billdate
    两张表判断赋值,都是NULL惹的祸…
    DataGridView使用初步
    在SQL Server 2005中启用“SQL Server”身份验证
    .Net学习笔记——细节问题
    C#调用带返回值的存储过程
    利用ASP.NET一般处理程序动态生成Web图像
    Windows Forms数据绑定技术
    C#中产生SQL语句的几种方式
    风讯dotNETCMS源码分析—数据存取篇
  • 原文地址:https://www.cnblogs.com/94cool/p/1795843.html
Copyright © 2011-2022 走看看