1.将整GridView的数据导出到Excel中关增加一个效果线做美化

最新的GridViewExport操作类

using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
 
namespace DotNet.Utilities
{
    /// <summary>
    /// Summary description for GridViewExport
    /// </summary>
    public class GridViewExport
    {
        public GridViewExport()
        {
            //
            // TODO: Add constructor logic here
            //
        }
 
        public static void Export(string fileName, GridView gv)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader(
                "content-disposition", string.Format("attachment; filename={0}", fileName));
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            //HttpContext.Current.Response.Charset = "utf-8";
 
 
            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    //  Create a form to contain the grid
                    Table table = new Table();
                    table.GridLines = GridLines.Both;  //单元格之间添加实线
 
                    //  add the header row to the table
                    if (gv.HeaderRow != null)
                    {
                        PrepareControlForExport(gv.HeaderRow);
                        table.Rows.Add(gv.HeaderRow);
                    }
 
                    //  add each of the data rows to the table
                    foreach (GridViewRow row in gv.Rows)
                    {
                        PrepareControlForExport(row);
                        table.Rows.Add(row);
                    }
 
                    //  add the footer row to the table
                    if (gv.FooterRow != null)
                    {
                        PrepareControlForExport(gv.FooterRow);
                        table.Rows.Add(gv.FooterRow);
                    }
 
                    //  render the table into the htmlwriter
                    table.RenderControl(htw);
 
                    //  render the htmlwriter into the response
                    HttpContext.Current.Response.Write(sw.ToString());
                    HttpContext.Current.Response.End();
                }
            }
        }
 
        /// <summary>
        /// Replace any of the contained controls with literals
        /// </summary>
        /// <param name="control"></param>
        private static void PrepareControlForExport(Control control)
        {
            for (int i = 0; i < control.Controls.Count; i++)
            {
                Control current = control.Controls;
                if (current is LinkButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
                }
                else if (current is ImageButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
                }
                else if (current is HyperLink)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
                }
                else if (current is DropDownList)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
                }
                else if (current is CheckBox)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
                }
 
                if (current.HasControls())
                {
                    PrepareControlForExport(current);
                }
            }
        }
 
 
        /// <summary>
        /// 导出Grid的数据(全部)到Excel
        /// 字段全部为BoundField类型时可用
        /// 要是字段为TemplateField模板型时就取不到数据
        /// </summary>
        /// <param name="grid">grid的ID</param>
        /// <param name="dt">数据源</param>
        /// <param name="excelFileName">要导出Excel的文件名</param>
        public static void OutputExcel(GridView grid, DataTable dt, string excelFileName)
        {
            Page page = (Page)HttpContext.Current.Handler;
            page.Response.Clear();
            string fileName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(excelFileName));
            page.Response.AddHeader("Content-Disposition", "attachment:filename=" + fileName + ".xls");
            page.Response.ContentType = "application/vnd.ms-excel";
            page.Response.Charset = "utf-8";
 
            StringBuilder s = new StringBuilder();
            s.Append("<HTML><HEAD><TITLE>" + fileName + "</TITLE><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>");
 
            int count = grid.Columns.Count;
 
            s.Append("<table border=1>");
            s.AppendLine("<tr>");
            for (int i = 0; i < count; i++)
            {
 
                if (grid.Columns.GetType() == typeof(BoundField))
                    s.Append("<td>" + grid.Columns.HeaderText + "</td>");
 
                //s.Append("<td>" + grid.Columns.HeaderText + "</td>");
 
            }
            s.Append("</tr>");
 
            foreach (DataRow dr in dt.Rows)
            {
                s.AppendLine("<tr>");
                for (int n = 0; n < count; n++)
                {
                    if (grid.Columns[n].Visible && grid.Columns[n].GetType() == typeof(BoundField))
                        s.Append("<td>" + dr[((BoundField)grid.Columns[n]).DataField].ToString() + "</td>");
 
                }
                s.AppendLine("</tr>");
            }
 
            s.Append("</table>");
            s.Append("</body></html>");
 
            page.Response.BinaryWrite(System.Text.Encoding.GetEncoding("utf-8").GetBytes(s.ToString()));
            page.Response.End();
        }
 
    }
}

C#GridViewExport帮助类,美化导出的更多相关文章

  1. [Excel] C#GridViewExport帮助类,美化导出 (转载)

    主要功能如下1.将整GridView的数据导出到Excel中关增加一个效果线做美化最新的GridViewExport操作类看下面代码吧 /// <summary> /// 类说明:Grid ...

  2. TAQSkinScrollBar 类美化滚动条再讨论

    再说:TAQSkinScrollBar 类美化滚动条,http://www.138soft.com/?p=156  里面有人提到不可以滚动 滚动的改善方法: unit AQSkinScrollBar; ...

  3. java工具类POI导出word

    1.新建一个word,里面填写内容,如: 2.导出wordjava类 /** * POI导出word测试 * @throws Exception */ @RequestMapping(value=&q ...

  4. tp5.1 phpspreadsheet- 工具类 导入导出(整合优化,非原创,抄一抄,加了一些自己的东西,)

    phpspreadsheet-工具类 导入导出(整合优化,非原创,抄一抄,加了一些自己的东西)1. composer require phpoffice/phpspreadsheet2. 看最下面的两 ...

  5. C#调用c++类的导出函数

    C# 需要调用C++东西,但是有不想做成COM,就只好先导出类中的函数处理. 不能直接调用,需单独导出函数 参考:http://blog.csdn.net/cartzhang/article/deta ...

  6. 基于phpExcel写的excel类(导出为Excel)

    <?php /* * 类的功能 * 传入二位数组导出excel * 传入excel 导出二位数组 * @author mrwu */ require('PHPExcel.php'); requi ...

  7. 工具类--Excel 导出poi

    实现功能 --批量导出excel 文件,配置一个sheet多少条数据,根据查询数据量的多少确定生成几个sheet页. pom 文件导入ExcelUtils工具包,依赖于poi包. <!-- ht ...

  8. 使用hutool工具类进行导出

    引入依赖为: <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</ ...

  9. 偷懒小工具 - Excel导出公共类

    说明 最近接了一个任务,就是做一个列表的Excel导出功能.并且有很多页面都会使用这个功能. 导出的Excel大体格式如图 很简单的列表,标题加背景色,然后不同类型,显示方式不一样.对齐方式不一样.不 ...

随机推荐

  1. app转让遇到的坑

    家人共享的一部分 首先我们要符合app转让的一些基本规定,填写正确的信息去申请转让.(google会有很多正确的转让步骤),这里我就不多写出来了. 当接收到接受app的时候会出现一些想不到的问题. 其 ...

  2. sqoop连接oracle与mysql&mariadb的错误

    错误说明: 由于我的hadoop的集群是用cloudera manager在线自动安装的,因此他们的安装路径必须遵循cloudera的规则,这里只有查看cloudera的官方文档了,请参考:http: ...

  3. 安装生物信息学软件-bowtie2

    好吧,这是本周(2016.10.21-28)的学习任务之一:安装bowtie2并学习其使用方法&参数设置 所以,啃文档咯,官方文档Version 2.2.9 http://bowtie-bio ...

  4. C++ iostream的线程安全性问题

    标准C里面的printf, fprintf之类的,会给FILE指针上锁(在unix平台上就是记录锁,按照msdn的说法windows上也有类似的锁),所以单次函数调用总是线程安全的: 要注意,这里只对 ...

  5. UIkit框架之UISegmentedControl

    1.继承链:UIcontrol:UIview:uiresponder:NSObject 2.初始化 (1)- (instancetype)initWithItems:(NSArray *)items ...

  6. 关于asp的运行环境配置

    xp系统的配置方法http://jingyan.baidu.com/article/4f7d571289ac441a201927da.html win7系统的配置方法http://jingyan.ba ...

  7. lua class(table)

    自己看吧: Base = {x = 0,y = 0} ---原型表 Base.name = "luohai"Base.age = 22Base.sex = "man&qu ...

  8. IIS32位,64位模式下切换

    一.32位模式 1.cscript %systemdrive%\inetpub\adminscripts\adsutil.vbs set w3svc/appPools/enable32bitappon ...

  9. oracle 小知识

    oracle: 数值随机的函数是 dbms_random.value(最大值,最小值)   用法是select dbms_random(3,0) from dual; oracle: 获取前100条 ...

  10. 我的STL之旅 MyList

    #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> // ...