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

 在web应用程序中,我们是不是很发愁打印问题,您是不是有过为了打印写Activex的经历,我们有没有想过,Word和Excel的打印功能能被我们利用起来呢?只要我们将我们将数据导出到Excel或者Word中,打印岂不是小case了么。下面就谈谈如何让GridView自己支持导出Excel和Word 。
    首先增加了两个属性,用于指示是否支持Excel导出和Word导出
 
None.gif    // 增加了一个设置是否显示“导出Word”按钮的属性
ExpandedBlockStart.gifContractedBlock.gif
         /**/ /// <summary>
InBlock.gif        
/// 排序提示信息
ExpandedBlockEnd.gif        
/// </summary>

None.gif         [
None.gif        Description(
" 显示导出到Word " ),
None.gif        Category(
" 扩展 " ),
None.gif         DefaultValue(
true )
None.gif        ]
None.gif        
public   virtual   bool  ShowExportWord
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
object obj2 = this.ViewState["ShowExportWord"];
InBlock.gif                
if (obj2 != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
return (bool)obj2;
ExpandedSubBlockEnd.gif                }

InBlock.gif                
return true;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
bool aShowExportWord = this.ShowExportWord;
InBlock.gif                
if (value != aShowExportWord)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
this.ViewState["ShowExportWord"= value;
InBlock.gif                    
if (base.Initialized)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
base.RequiresDataBinding = true;
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }

None.gif        
// 增加了一个设置是否显示“导出Excel”按钮的属性
None.gif
        [
None.gif       Description(
" 显示导出到Excel " ),
None.gif       Category(
" 扩展 " ),
None.gif       DefaultValue(
true )
None.gif       ]
None.gif        
public   virtual   bool  ShowExportExcel
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
object obj2 = this.ViewState["ShowExportExcel"];
InBlock.gif                
if (obj2 != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
return (bool)obj2;
ExpandedSubBlockEnd.gif                }

InBlock.gif                
return true;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
bool aShowExportExcel = this.ShowExportExcel;
InBlock.gif                
if (value != aShowExportExcel)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
this.ViewState["ShowExportExcel"= value;
InBlock.gif                    
if (base.Initialized)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
base.RequiresDataBinding = true;
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }
声明两个LinkButton控件btnExportWord,btnExport,分别用于点击导出Excel和点击导出word,并在控件的OnInit事件中初始化两个控件
ContractedBlock.gif ExpandedBlockStart.gif 声明两个LinkButton,并在控件的OnInit中初始化
None.gif   LinkButton btnExportWord;
None.gif        LinkButton btnExport; 
protected override void OnInit(EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            
this.EnableViewState = true;
InBlock.gif
InBlock.gif
InBlock.gif            btnExport 
= new LinkButton();
InBlock.gif            btnExport.CommandName 
= "ExportToExcel";
InBlock.gif            btnExport.EnableViewState 
= true;
InBlock.gif            btnExport.Text 
= "导出Excel";
InBlock.gif
InBlock.gif            btnExportWord 
= new LinkButton();
InBlock.gif            btnExportWord.CommandName 
= "ExportToWord";
InBlock.gif            btnExportWord.EnableViewState 
= true;
InBlock.gif            btnExportWord.Text 
= "导出Word";
InBlock.gif 
base.OnInit(e);
ExpandedBlockEnd.gif        }

将两个LinkButton添加到GridView子控件中。
ExpandedBlockStart.gif ContractedBlock.gif   protected   override   int  CreateChildControls(System.Collections.IEnumerable dataSource,  bool  dataBinding)  dot.gif {
InBlock.gif            
int res = base.CreateChildControls(dataSource, dataBinding);
InBlock.gif                
try
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    GridViewRow row 
= new GridViewRow(00, DataControlRowType.Pager, DataControlRowState.Normal);  TableCell cell2 = new TableCell();
InBlock.gif                    cell2.HorizontalAlign 
= HorizontalAlign.Right;
InBlock.gif                    cell2.Wrap 
= falseif (this.ShowExportExcel == true)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        l1 
= new Literal();
InBlock.gif                        l1.Text 
= " [";
InBlock.gif                        cell2.Controls.Add(l1);
InBlock.gif                        cell2.Controls.Add(btnExport);
InBlock.gif                        l1 
= new Literal();
InBlock.gif                        l1.Text 
= "";
InBlock.gif                        cell2.Controls.Add(l1);
ExpandedSubBlockEnd.gif                    }

InBlock.gif
InBlock.gif                    
if (this.ShowExportWord == true)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        l1 
= new Literal();
InBlock.gif                        l1.Text 
= " [";
InBlock.gif                        cell2.Controls.Add(l1);
InBlock.gif                        cell2.Controls.Add(btnExportWord);
InBlock.gif                        l1 
= new Literal();
InBlock.gif                        l1.Text 
= "";
InBlock.gif                        cell2.Controls.Add(l1);
ExpandedSubBlockEnd.gif                    }
 r.Cells.Add(cell2);
InBlock.gif                    
this.Controls[0].Controls.AddAt(0, row);
ExpandedSubBlockEnd.gif                }

InBlock.gif                
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
ExpandedSubBlockEnd.gif                }

ExpandedBlockEnd.gif            }

None.gif            
return  res;
None.gif        }
在导出的时候,我们希望一些列不被导出,如修改,删除这样的列,因此我们添加了这样的一个属性
ContractedBlock.gif ExpandedBlockStart.gif 用于指定不被导出列,列名之间用,隔开
None.gif  string _UnExportedColumnNames = "";
None.gif        [
None.gif  Description(
"不导出的数据列集合,将HeaderText用,隔开"),
None.gif  Category(
"扩展"),
None.gif        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
None.gif        PersistenceMode(PersistenceMode.InnerProperty)
None.gif
None.gif  ]
None.gif        
public string UnExportedColumnNames
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return _UnExportedColumnNames;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                _UnExportedColumnNames 
= value;
ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }
在导出的时候,原来的GridView列表中会有一些LinkButton或者DropDownList控件,导出的时候,我们也希望将其换成纯文本,用下面这个函数可以完成这个目的
ContractedBlock.gif ExpandedBlockStart.gif 用于将GridView中的LinkButton和DropDownList转换成文本的方法
None.gif private void DisableControls(Control gv)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif
InBlock.gif            LinkButton lb 
= new LinkButton();
InBlock.gif
InBlock.gif            Literal l 
= new Literal();
InBlock.gif
InBlock.gif            
string name = String.Empty;
InBlock.gif
InBlock.gif            
for (int i = 0; i < gv.Controls.Count; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif
InBlock.gif                
if (gv.Controls[i].GetType() == typeof(LinkButton))
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif
InBlock.gif                    l.Text 
= (gv.Controls[i] as LinkButton).Text;
InBlock.gif
InBlock.gif                    gv.Controls.Remove(gv.Controls[i]);
InBlock.gif
InBlock.gif                    gv.Controls.AddAt(i, l);
InBlock.gif
ExpandedSubBlockEnd.gif                }

InBlock.gif                
else if (gv.Controls[i].GetType() == typeof(DropDownList))
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    l.Text 
= (gv.Controls[i] as DropDownList).SelectedItem.Text;
InBlock.gif
InBlock.gif                    gv.Controls.Remove(gv.Controls[i]);
InBlock.gif
InBlock.gif                    gv.Controls.AddAt(i, l);
InBlock.gif
ExpandedSubBlockEnd.gif                }

InBlock.gif
InBlock.gif                
if (gv.Controls[i].HasControls())
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    DisableControls(gv.Controls[i]);
ExpandedSubBlockEnd.gif                }

InBlock.gif
ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }

None.gif
下面是处理ItemCommand,将GridView导出的代码
ContractedBlock.gif ExpandedBlockStart.gif 处理OnRowCommand事件,将GridView数据导出到Excel和Word
None.gif  protected override void OnRowCommand(GridViewCommandEventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            
base.OnRowCommand(e);
InBlock.gif            
if (e.CommandName == "ExportToExcel")
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
string[] ss = UnExportedColumnNames.Split(',');
InBlock.gif                System.Collections.Generic.List
<string> list = new System.Collections.Generic.List<string>();
InBlock.gif
InBlock.gif                
foreach (string s in ss)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
if (s != ",")
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        list.Add(s);
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

InBlock.gif                ShowToolBar 
= false;
InBlock.gif                
this.AllowSorting = false;
InBlock.gif                HttpContext.Current.Response.Clear();
InBlock.gif
InBlock.gif                HttpContext.Current.Response.AddHeader(
"content-disposition",
InBlock.gif                
"attachment;filename=" + ExcelFileName + ".xls");
InBlock.gif
InBlock.gif                HttpContext.Current.Response.Charset 
= "GB2312";
InBlock.gif                HttpContext.Current.Response.ContentEncoding 
= System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
InBlock.gif
                HttpContext.Current.Response.ContentType = "application/ms-excel";
InBlock.gif
InBlock.gif
InBlock.gif                System.IO.StringWriter stringWrite 
= new System.IO.StringWriter();
InBlock.gif
InBlock.gif                System.Web.UI.HtmlTextWriter htmlWrite 
=
InBlock.gif                
new HtmlTextWriter(stringWrite);
InBlock.gif
InBlock.gif                
bool showCheckAll = ShowCheckAll;
InBlock.gif                
this.ShowCheckAll = false;
InBlock.gif                
this.AllowPaging = false;
InBlock.gif                OnBind();
InBlock.gif                DisableControls(
this);
InBlock.gif                
foreach (DataControlField c in this.Columns)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
if (list.Contains(c.HeaderText) && !string.IsNullOrEmpty(c.HeaderText))
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        c.Visible 
= false;
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

InBlock.gif                
this.RenderControl(htmlWrite);
InBlock.gif                
string content = System.Text.RegularExpressions.Regex.Replace(stringWrite.ToString(), "(<a[^>]+>)|(</a>)""");
InBlock.gif                HttpContext.Current.Response.Write(content);
InBlock.gif
InBlock.gif                HttpContext.Current.Response.End();
InBlock.gif
InBlock.gif                
this.AllowPaging = true;
InBlock.gif                
this.AllowSorting = true;
InBlock.gif                ShowToolBar 
= true;
InBlock.gif                
this.ShowCheckAll = showCheckAll;
InBlock.gif                OnBind();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else if (e.CommandName == "ExportToWord")
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
string[] ss = UnExportedColumnNames.Split(',');
InBlock.gif                System.Collections.Generic.List
<string> list = new System.Collections.Generic.List<string>();
InBlock.gif
InBlock.gif                
foreach (string s in ss)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
if (s != ",")
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        list.Add(s);
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

InBlock.gif                ShowToolBar 
= false;
InBlock.gif                
this.AllowSorting = false;
InBlock.gif                HttpContext.Current.Response.Clear();
InBlock.gif
InBlock.gif                HttpContext.Current.Response.AddHeader(
"content-disposition",
InBlock.gif                
"attachment;filename=" + ExcelFileName + ".doc");
InBlock.gif
InBlock.gif                HttpContext.Current.Response.Charset 
= "GB2312";
InBlock.gif                HttpContext.Current.Response.ContentEncoding 
= System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
InBlock.gif
                HttpContext.Current.Response.ContentType = "application/ms-word";
InBlock.gif
InBlock.gif
InBlock.gif                System.IO.StringWriter stringWrite 
= new System.IO.StringWriter();
InBlock.gif
InBlock.gif                System.Web.UI.HtmlTextWriter htmlWrite 
=
InBlock.gif                
new HtmlTextWriter(stringWrite);
InBlock.gif
InBlock.gif                
bool showCheckAll = ShowCheckAll;
InBlock.gif                
this.ShowCheckAll = false;
InBlock.gif                
this.AllowPaging = false;
InBlock.gif                OnBind();
InBlock.gif
InBlock.gif                DisableControls(
this);
InBlock.gif                
foreach (DataControlField c in this.Columns)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
if (list.Contains(c.HeaderText) && !string.IsNullOrEmpty(c.HeaderText))
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        c.Visible 
= false;
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

InBlock.gif                
this.RenderControl(htmlWrite);
InBlock.gif                
string content = System.Text.RegularExpressions.Regex.Replace(stringWrite.ToString(), "(<a[^>]+>)|(</a>)""");
InBlock.gif                HttpContext.Current.Response.Write(content);
InBlock.gif
InBlock.gif                HttpContext.Current.Response.End();
InBlock.gif
InBlock.gif                
this.AllowPaging = true;
InBlock.gif                
this.AllowSorting = true;
InBlock.gif                ShowToolBar 
= true;
InBlock.gif                ShowCheckAll 
= showCheckAll;
InBlock.gif                OnBind();
ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }

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

转载于:https://www.cnblogs.com/yohen/articles/822296.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值