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[i];
                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[i].GetType() == typeof(BoundField))
                    s.Append("<td>" + grid.Columns[i].HeaderText + "</td>");

//s.Append("<td>" + grid.Columns[i].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#实现GridView导出Excel的更多相关文章

  1. Asp.net Gridview导出Excel

    前台页面放一个GridView什么的就不说了,要注意的是在 <%@ Page Language="C#" AutoEventWireup="true" C ...

  2. GridView导出Excel的超好样例

    事实上网上有非常多关于Excel的样例,可是不是非常好,他们的代码没有非常全,读的起来还非常晦涩.经过这几天的摸索,最终能够完毕我想要导出报表Excel的效果了.以下是我的效果图. 一.前台的页面图 ...

  3. ASP.NET gridview导出excel,防止繁体产生有乱码的方式

    //1.先引用比如 : using System; using System.Collections.Generic; using System.Linq; using System.Web; usi ...

  4. GridView导出excel格式问题

    在导出的点击事件中,代码如下: //指定导出对应单元格为文本样式 string style = @"<style> .test { vnd.ms-excel.numberform ...

  5. C# GridView 导出Excel表

    出错1:类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内解决方案:在后台文件中重载VerifyRenderingInServerForm方法,如 ...

  6. GridView导出Excel(中文乱码)

    public void OUTEXCEL(string items,string where) { DataSet ds = new StudentBLL().GetTable(items,where ...

  7. GridView导出Excel

    public void OUTEXCEL() { DataSet ds = new GW_T_DemandDAL().GetWzH(GetPersonInfoData(UserInfo), Reque ...

  8. GridView 导出Excel

    protected void btnExcel_Click(object sender, EventArgs e) { ) { ExportGridViewForUTF8(GridView1, Dat ...

  9. C#通过gridview导出excel

    [CustomAuthorize]        public FileResult ExportQuestionCenterExcel(SearchBaseQuestion search)      ...

随机推荐

  1. 学习计划(一)——JavaScript

    一:与前端之缘 大一时除了上课和社团外不知道要学点什么,但是又不想睡觉打游戏,常常就是啥都想学,photoshop,premiere,After Effects都学,但始终没有明确的目标. 大二时一直 ...

  2. 点击弹窗后再刷新html页面

    当alert弹出框点击确定以后,再让页面重新加载一下 具体的代码如下: <script type="text/javascript"> alert("签到成功 ...

  3. 笑谈ArcToolbox (2) 开启ArcToolbox的钥匙

    笑谈ArcToolbox (2) 开启ArcToolbox的钥匙 by 李远祥 GIS人遇到ArcToolbox就像找到了宝藏一样兴奋,但并不是每个找到宝藏的人都具备开启宝藏的钥匙.有时候功能强大并不 ...

  4. foreach和for循环的区别

    for循环 for循环,通过下标,对循环中的代码反复执行,功能强大,可以通过index取得元素.在处理比较复杂的处理的时候较为方便. foreach循环 foreach,从头到尾,对于集合中的对象遍历 ...

  5. (C#)xml的简单理解创建和读取

    xml知识点清理:一.文档规则 1.区分大小写. 2.属性值必须加引号(单引号.双引号都可以),一般情况下建议使用使用双引号. 3.所有标记必须有结束符号. 4.所有空标记必须关闭. 5.必须有且仅有 ...

  6. C++inserter

    C++的迭代器适配器中常用的有插入迭代器(Inser Iterator).流迭代器(Stream Iterator)和逆向迭代器(Reverse Iterator)等! 本文主要是介绍插入迭代器(In ...

  7. Radis安装

    基本知识 1.Redis的数据类型: 字符串.列表(lists).集合(sets).有序集合(sorts sets).哈希表(hashs) 2.Redis和memcache相比的独特之处: (1)re ...

  8. 部署lamp

  9. 前端总结·基础篇·JS(一)五大数据类型之字符串(String)

    前端总结系列 前端总结·基础篇·CSS(一)布局 前端总结·基础篇·CSS(二)视觉 前端总结·基础篇·CSS(二)补充 前端总结·基础篇·JS(一)五大数据类型之字符串(String) 目录 这是& ...

  10. UI设计需具备的几大素质

    近年来,IT产业对于高端技术人才需求加大,特别是北上广和知名企业对人才需求更为迫切,UI设计人员的正在接受UI培训的学员都赢认识到UI设计在未来要求将越来越高,交互设计越来越新颖也将对用户更加友好,兄 ...