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. 网页首页制作总结(div+css+javascript)

    一.对网页整体布局,分几个版块 如下图所示: 确定布局之后,规划好网页,准备素材,按照标准文档流的顺序,从上到下,从左到右写入代码. 以上图为例,分为两部分,红色的主体部分和页脚.主体部分分割为头部. ...

  2. redhat6.4安装storm集群-4节点

    0.搭建ftp服务器并建立yum源 1.在每个节点上安装java并设置环境变量 2.在三个节点上安装zookeeper 3.安装zeromq 过程中发现运行./configure时出现问题: conf ...

  3. The Layout Process on Mac OSX and iOS

    First we will recap the steps it takes to bring views on screen with Auto Layout enabled. When you’r ...

  4. angular 国际化

    今天mentor说让我看看angular国际化的问题,我看了看,发现这个帖子很有价值,但是手头上还有好几个issue没有解决,所以就先考皮在这将连接,解决完这几个bug我再去细细研究这个问题, htt ...

  5. yum命令详解

    yum(全 称为 Yellow dog Updater, Modified)是一个在Fedora和RedHat以及SUSE中的Shell前端软件包管理器.基於RPM包管理,能够从指定的服务器自动下载 ...

  6. C语言之EOF和feof()

    EOF用于判断所操作的文件是否已经读到文件结束,是在stdio.h文件中定义的符号常量,值为-1. 即当系统读取到文件结尾,所返回的一个信号值(也就是-1). EOF不是可输出字符,因此不能在屏幕上输 ...

  7. javascript 中的 delete

    那么,为什么我们能删除一个对象的属性: var x = { a: 1 }; delete x.a; // true x.a; // undefined 但却不能删除一个变量: var x = 1; d ...

  8. Android应用程序“R文件”消失

    其实Android自己维护这一个 public final class R类主要是跟新资源文件,这个R.java无需我们自己去修改,如果你不了解千万不要去修改它,它定义的每个资源值都是唯一的,不会和系 ...

  9. 将JZ2440的调试串口换成com2

    众所周知JZ2440 V3很小巧,精致.今天单就JZ2440的串口来讨论一些问题.我们在用串口进行调试的时候,需要用JZ2440自带的一根USB线连接电脑USB口和开发板的USB-com1口.先来看一 ...

  10. MongoDB学习笔记二:创建、更新及删除文档

    插入并保存文档 对目标集使用insert方法插入一个文档: > db.foo.insert({"bar" : "baz"}) 这个操作会给文档增加一个&q ...