zoukankan      html  css  js  c++  java
  • .net中将DataTable导出到word、Excel、txt、htm的方法

    dt:DataTable

    strFile:fileName

    strExt:type


    private void GridExport(DataTable dt, string strFile, string strExt)
        {
            string strAppType = "";
            switch (strExt)
            {
                case "xls":
                    strAppType = "application/ms-excel";
                    break;
                case "doc":
                    strAppType = "application/ms-word";
                    break;
                case "txt":
                    strAppType = "application/ms-txt";
                    break;
                case "html":
                case "htm":
                    strAppType = "application/ms-html";
                    break;
                default: return;
            }
            GridView MyGridView = new GridView();
            MyGridView.DataSource = dt;
            MyGridView.DataBind(); 
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.AddHeader("Content-Type", "text/html; charset=GB2312");
            HttpContext.Current.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.{1}", HttpUtility.UrlEncode(strFile,Encoding.GetEncoding("GB2312")), strExt));
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); 
            HttpContext.Current.Response.ContentType = strAppType; 
            //MyGridView.Page.EnableViewState = false;
            //二、定义一个输入流
            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            //三、将目标数据绑定到输入流输出
            MyGridView.RenderControl(oHtmlTextWriter);
            HttpContext.Current.Response.Write(oStringWriter.ToString());
            HttpContext.Current.Response.End();
        }

  • 相关阅读:
    【洛谷】1852:[国家集训队]跳跳棋【LCA】【倍增?】
    【POJ】1835:宇航员【模拟】【三维行走】
    【BZOJ】3195: [Jxoi2012]奇怪的道路【状压/奇偶性】【思路】
    【10.24校内测试】【欧拉路径(有向+无向)】【双向链表/树状数组/线段树】
    【POJ】1840:Eqs【哈希表】
    【洛谷】4317:花神的数论题【数位DP】
    【POJ】1486:Sorting Slides【二分图关键边判定】
    算法模板
    Redis源码阅读一:简单动态字符串SDS
    总结下c/c++的一些调试经验
  • 原文地址:https://www.cnblogs.com/lxshanye/p/4058407.html
Copyright © 2011-2022 走看看