Asp.net源码交流论坛 Asp.net交流讨论区Asp.net技术文章手把手教你如何扩展GridView之自带Excel和Word导出

1  /  3  页    1  2  3  跳转
发表新主题 回复该主题

标题: 手把手教你如何扩展GridView之自带Excel和Word导出

本主题由 董事长 51aspx 于 2008-7-18 10:16:06 执行 移动主题 操作

身份:部门主管

 
  • UID:26
  • 来自:
  • 精华:2
  • 积分:120
  • 帖子:104
  • 注册: 2007-05-26
  • 状态: 离线
  • 威望:6.00
  • 金钱:19.80 元

手把手教你如何扩展GridView之自带Excel和Word导出

在web应用程序中,我们是不是很发愁打印问题,您是不是有过为了打印写Activex的经历,我们有没有想过,Word和Excel的打印功能能被我们利用起来呢?只要我们将我们将数据导出到Excel或者Word中,打印岂不是小case了么。下面就谈谈如何让GridView自己支持导出Excel和Word 。
    首先增加了两个属性,用于指示是否支持Excel导出和Word导出

  //增加了一个设置是否显示“导出Word”按钮的属性
        /**//// <summary>
        /// 排序提示信息
        /// </summary>
        [
        Description(&quot;显示导出到Word&quot;),
        Category(&quot;扩展&quot;),
        DefaultValue(true)
        ]
        public virtual bool ShowExportWord
        {
            get
            {
                object obj2 = this.ViewState[&quot;ShowExportWord&quot;];
                if (obj2 != null)
                {
                    return (bool)obj2;
                }
                return true;
            }
            set
            {
                bool aShowExportWord = this.ShowExportWord;
                if (value != aShowExportWord)
                {
                    this.ViewState[&quot;ShowExportWord&quot;] = value;
                    if (base.Initialized)
                    {
                        base.RequiresDataBinding = true;
                    }
                }
            }
        }
        //增加了一个设置是否显示“导出Excel”按钮的属性
        [
      Description(&quot;显示导出到Excel&quot;),
      Category(&quot;扩展&quot;),
      DefaultValue(true)
      ]
        public virtual bool ShowExportExcel
        {
            get
            {
                object obj2 = this.ViewState[&quot;ShowExportExcel&quot;];
                if (obj2 != null)
                {
                    return (bool)obj2;
                }
                return true;
            }
            set
            {
                bool aShowExportExcel = this.ShowExportExcel;
                if (value != aShowExportExcel)
                {
                    this.ViewState[&quot;ShowExportExcel&quot;] = value;
                    if (base.Initialized)
                    {
                        base.RequiresDataBinding = true;
                    }
                }
            }
        }


声明两个LinkButton控件btnExportWord,btnExport,分别用于点击导出Excel和点击导出word,并在控件的OnInit事件中初始化两个控件
声明两个LinkButton,并在控件的OnInit中初始化


  LinkButton btnExportWord;
        LinkButton btnExport; protected override void OnInit(EventArgs e)
        {
            this.EnableViewState = true;

            btnExport = new LinkButton();
            btnExport.CommandName = &quot;ExportToExcel&quot;;
            btnExport.EnableViewState = true;
            btnExport.Text = &quot;导出Excel&quot;;
            btnExportWord = new LinkButton();
            btnExportWord.CommandName = &quot;ExportToWord&quot;;
            btnExportWord.EnableViewState = true;
            btnExportWord.Text = &quot;导出Word&quot;;
base.OnInit(e);
        }


将两个LinkButton添加到GridView子控件中。


protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding) {
            int res = base.CreateChildControls(dataSource, dataBinding);
                try
                {
                    GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Pager, DataControlRowState.Normal);  TableCell cell2 = new TableCell();
                    cell2.HorizontalAlign = HorizontalAlign.Right;
                    cell2.Wrap = false; if (this.ShowExportExcel == true)
                    {
                        l1 = new Literal();
                        l1.Text = &quot; [&quot;;
                        cell2.Controls.Add(l1);
                        cell2.Controls.Add(btnExport);
                        l1 = new Literal();
                        l1.Text = &quot;] &quot;;
                        cell2.Controls.Add(l1);
                    }
                    if (this.ShowExportWord == true)
                    {
                        l1 = new Literal();
                        l1.Text = &quot; [&quot;;
                        cell2.Controls.Add(l1);
                        cell2.Controls.Add(btnExportWord);
                        l1 = new Literal();
                        l1.Text = &quot;] &quot;;
                        cell2.Controls.Add(l1);
                    } r.Cells.Add(cell2);
                    this.Controls[0].Controls.AddAt(0, row);
                }
                catch
                {
                }
            }
            return res;
        }


在导出的时候,我们希望一些列不被导出,如修改,删除这样的列,因此我们添加了这样的一个属性
用于指定不被导出列,列名之间用,隔开


string _UnExportedColumnNames = &quot;&quot;;
        [
  Description(&quot;不导出的数据列集合,将HeaderText用,隔开&quot;),
  Category(&quot;扩展&quot;),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        PersistenceMode(PersistenceMode.InnerProperty)
  ]
        public string UnExportedColumnNames
        {
            get
            {
                return _UnExportedColumnNames;
            }
            set
            {
                _UnExportedColumnNames = value;
            }
        }


在导出的时候,原来的GridView列表中会有一些LinkButton或者DropDownList控件,导出的时候,我们也希望将其换成纯文本,用下面这个函数可以完成这个目的
用于将GridView中的LinkButton和DropDownList转换成文本的方法


private void DisableControls(Control gv)
        {
            LinkButton lb = new LinkButton();
            Literal l = new Literal();
            string name = String.Empty;
            for (int i = 0; i < gv.Controls.Count; i++)
            {
                if (gv.Controls[i].GetType() == typeof(LinkButton))
                {
                    l.Text = (gv.Controls[i] as LinkButton).Text;
                    gv.Controls.Remove(gv.Controls[i]);
                    gv.Controls.AddAt(i, l);
                }
                else if (gv.Controls[i].GetType() == typeof(DropDownList))
                {
                    l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
                    gv.Controls.Remove(gv.Controls[i]);
                    gv.Controls.AddAt(i, l);
                }
                if (gv.Controls[i].HasControls())
                {
                    DisableControls(gv.Controls[i]);
                }
            }
        }


下面是处理ItemCommand,将GridView导出的代码
处理OnRowCommand事件,将GridView数据导出到Excel和Word


  protected override void OnRowCommand(GridViewCommandEventArgs e)
        {
            base.OnRowCommand(e);
            if (e.CommandName == &quot;ExportToExcel&quot;)
            {
                string[] ss = UnExportedColumnNames.Split(',');
                System.Collections.Generic.List<string> list = new System.Collections.Generic.List<string>();
                foreach (string s in ss)
                {
                    if (s != &quot;,&quot;)
                    {
                        list.Add(s);
                    }
                }
                ShowToolBar = false;
                this.AllowSorting = false;
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.AddHeader(&quot;content-disposition&quot;,
                &quot;attachment;filename=&quot; + ExcelFileName + &quot;.xls&quot;);
                HttpContext.Current.Response.Charset = &quot;GB2312&quot;;
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding(&quot;GB2312&quot;);//设置输出流为简体中文
                HttpContext.Current.Response.ContentType = &quot;application/ms-excel&quot;;

                System.IO.StringWriter stringWrite = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter htmlWrite =
                new HtmlTextWriter(stringWrite);
                bool showCheckAll = ShowCheckAll;
                this.ShowCheckAll = false;
                this.AllowPaging = false;
                OnBind();
                DisableControls(this);
                foreach (DataControlField c in this.Columns)
                {
                    if (list.Contains(c.HeaderText) &amp;&amp; !string.IsNullOrEmpty(c.HeaderText))
                    {
                        c.Visible = false;
                    }
                }
                this.RenderControl(htmlWrite);
                string content = System.Text.RegularExpressions.Regex.Replace(stringWrite.ToString(), &quot;(<a[^>]+>)|(</a>)&quot;, &quot;&quot;);
                HttpContext.Current.Response.Write(content);
                HttpContext.Current.Response.End();
                this.AllowPaging = true;
                this.AllowSorting = true;
                ShowToolBar = true;
                this.ShowCheckAll = showCheckAll;
                OnBind();
            }
            else if (e.CommandName == &quot;ExportToWord&quot;)
            {
                string[] ss = UnExportedColumnNames.Split(',');
                System.Collections.Generic.List<string> list = new System.Collections.Generic.List<string>();
                foreach (string s in ss)
                {
                    if (s != &quot;,&quot;)
                    {
                        list.Add(s);
                    }
                }
                ShowToolBar = false;
                this.AllowSorting = false;
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.AddHeader(&quot;content-disposition&quot;,
                &quot;attachment;filename=&quot; + ExcelFileName + &quot;.doc&quot;);
                HttpContext.Current.Response.Charset = &quot;GB2312&quot;;
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding(&quot;GB2312&quot;);//设置输出流为简体中文
                HttpContext.Current.Response.ContentType = &quot;application/ms-word&quot;;

                System.IO.StringWriter stringWrite = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter htmlWrite =
                new HtmlTextWriter(stringWrite);
                bool showCheckAll = ShowCheckAll;
                this.ShowCheckAll = false;
                this.AllowPaging = false;
                OnBind();
                DisableControls(this);
                foreach (DataControlField c in this.Columns)
                {
                    if (list.Contains(c.HeaderText) &amp;&amp; !string.IsNullOrEmpty(c.HeaderText))
                    {
                        c.Visible = false;
                    }
                }
                this.RenderControl(htmlWrite);
                string content = System.Text.RegularExpressions.Regex.Replace(stringWrite.ToString(), &quot;(<a[^>]+>)|(</a>)&quot;, &quot;&quot;);
                HttpContext.Current.Response.Write(content);
                HttpContext.Current.Response.End();
                this.AllowPaging = true;
                this.AllowSorting = true;
                ShowToolBar = true;
                ShowCheckAll = showCheckAll;
                OnBind();
            }
        }


使用的时候,只要指定ShowExportExcel=True,ShowExportWord=True就自动出现导出Word和导出Excel的按钮了,点击自动会将GridView中的数据导出到Word或者Excel中了,如果原GridView是多页的,那也会自动将全部数据(而不是当前页的数据)导出,而且会剔除原来数据中的一些超级链接。使用起来相当简单,效果页非常好。

作者:jillzhang

51aspx 最后编辑于 2007-11-29 19:16:27
 
广告位招租,我换新头像了阿
引用 回复
 

身份:学员

 
  • UID:128
  • 来自:
  • 精华:0
  • 积分:8
  • 帖子:8
  • 注册: 2007-06-11
  • 状态: 离线
  • 威望:0.00
  • 金钱:0.95 元

回复:手把手教你如何扩展GridView之自带Excel和Word导出

不错,学习了,帮顶了。
引用 回复
 

身份:部门主管

 
  • UID:6
  • 来自:
  • 精华:0
  • 积分:4
  • 帖子:4
  • 注册: 2007-05-19
  • 状态: 离线
  • 威望:0.00
  • 金钱:1.40 元

回复:手把手教你如何扩展GridView之自带Excel和Word导出

学习,谢谢楼主分享
引用 回复
 

身份:学员

 
  • UID:3476
  • 来自:西安
  • 精华:0
  • 积分:7
  • 帖子:7
  • 注册: 2007-12-25
  • 状态: 离线
  • 威望:0.00
  • 金钱:0.85 元

回复:手把手教你如何扩展GridView之自带Excel和Word导出

引用 回复
 
2008-04-03 15:45
|

身份:学员

 
  • UID:3976
  • 来自:
  • 精华:0
  • 积分:6
  • 帖子:6
  • 注册: 2007-12-29
  • 状态: 离线
  • 威望:0.00
  • 金钱:0.60 元

回复:手把手教你如何扩展GridView之自带Excel和Word导出

讲的还不是很详细。
  不过还是谢谢了
引用 回复
 

身份:学员

 
  • UID:12253
  • 来自:
  • 精华:0
  • 积分:4
  • 帖子:4
  • 注册: 2008-04-03
  • 状态: 离线
  • 威望:0.00
  • 金钱:0.40 元

回复:手把手教你如何扩展GridView之自带Excel和Word导出

谢谢,试试
引用 回复
 

身份:学员

 
  • UID:5950
  • 来自:
  • 精华:0
  • 积分:36
  • 帖子:37
  • 注册: 2008-01-24
  • 状态: 离线
  • 威望:0.00
  • 金钱:4.30 元

回复:手把手教你如何扩展GridView之自带Excel和Word导出

再详细些就更好了
引用 回复
 

身份:工程师

 
  • UID:2045
  • 来自:安徽省铜菱
  • 精华:1
  • 积分:341
  • 帖子:297
  • 注册: 2007-12-07
  • 状态: 离线
  • 威望:39.00
  • 金钱:85.10 元

回复:手把手教你如何扩展GridView之自带Excel和Word导出

呵呵,又要学习了!
 
http://blog.163.com/chy2z/
引用 回复
 

身份:部门主管

 
  • UID:9044
  • 来自:河北省
  • 精华:0
  • 积分:238
  • 帖子:216
  • 注册: 2008-03-07
  • 状态: 离线
  • 威望:25.00
  • 金钱:23.85 元

回复:手把手教你如何扩展GridView之自带Excel和Word导出

这个嘛!其实有的用户就是不想导出,就让在程序里打印...只能用水晶报表啦..还有你做一个例题放到源码/资源供求里不更好么?
引用 回复
 

身份:工程师

 
  • UID:11087
  • 来自:内蒙古
  • 精华:0
  • 积分:129
  • 帖子:119
  • 注册: 2008-03-25
  • 状态: 离线
  • 威望:10.00
  • 金钱:12.35 元

回复:手把手教你如何扩展GridView之自带Excel和Word导出

正需要这个 学习了
引用 回复
 
1  /  3  页    1  2  3  跳转
发表新主题 回复该主题

现在时间是:2008-11-23 23:46:40 京ICP备06046876号