扩展GridView(八)——导出为Excel

GridView既强大又好用。为了让它更强大、更好用,我们来写一个继承自GridView的控件。
[源码下载]


扩展GridView(八)——导出为Excel


介绍
把GridView导出为一个Excel文件算是一个经常要用到的功能,也比较简单,我们来扩展一个GridView以实现这样的功能。


控件开发
1、新建一个继承自GridView的类。
ExpandedBlockStart.gif ContractedBlock.gif /**/ /// <summary>
InBlock.gif
/// 继承自GridView
ExpandedBlockEnd.gif
/// </summary>

None.gif [ToolboxData( @" <{0}:SmartGridView runat='server'></{0}:SmartGridView> " )]
None.gif
public   class  SmartGridView : GridView
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedBlockEnd.gif}

2、重写OnRowCommand,以实现把GridView导出为Excel的功能
ExpandedBlockStart.gif ContractedBlock.gif          /**/ /// <summary>
InBlock.gif        
/// OnRowCommand
InBlock.gif        
/// </summary>
ExpandedBlockEnd.gif        
/// <param name="e"></param>

None.gif          protected   override   void  OnRowCommand(GridViewCommandEventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
if (e.CommandName.ToLower() == "exporttoexcel")
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                System.Web.HttpContext.Current.Response.ClearContent();
InBlock.gif                
// e.CommandArgument用“;”隔开两部分,左边的部分为导出Excel的文件名称
InBlock.gif
                System.Web.HttpContext.Current.Response.AddHeader("content-disposition""attachment; filename=" + e.CommandArgument.ToString().Split(';')[0+ ".xls");
InBlock.gif                System.Web.HttpContext.Current.Response.ContentType 
= "application/excel";
InBlock.gif
InBlock.gif                System.IO.StringWriter sw 
= new System.IO.StringWriter();
InBlock.gif                HtmlTextWriter htw 
= new HtmlTextWriter(sw);
InBlock.gif
InBlock.gif                
// e.CommandArgument用“;”隔开两部分,右边的部分为需要隐藏的列的索引(列索引用“,”分开)
InBlock.gif
                if (e.CommandArgument.ToString().Split(';').Length > 1)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
foreach (string s in e.CommandArgument.ToString().Split(';')[1].Split(','))
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
int i;
InBlock.gif
InBlock.gif                        
if (!Int32.TryParse(s, out i))
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            
throw new ArgumentException("需要隐藏的列的索引不是整数"); 
ExpandedSubBlockEnd.gif                        }

InBlock.gif
InBlock.gif                        
if (i > this.Columns.Count)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            
throw new ArgumentOutOfRangeException("需要隐藏的列的索引超出范围");
ExpandedSubBlockEnd.gif                        }

InBlock.gif
InBlock.gif                        
this.Columns[i].Visible = false;
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

InBlock.gif
InBlock.gif                
// 隐藏“导出Excel”按钮
InBlock.gif
                ((Control)e.CommandSource).Visible = false;
InBlock.gif
InBlock.gif                
// 如果HeaderRow里的控件是button的话,则把它替换成文本
InBlock.gif
                foreach (TableCell tc in this.HeaderRow.Cells)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
// TableCell里的每个Control
InBlock.gif
                    foreach (Control c in tc.Controls)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
// 如果控件继承自接口IButtonControl
InBlock.gif
                        if (c.GetType().GetInterface("IButtonControl"!= null && c.GetType().GetInterface("IButtonControl").Equals(typeof(IButtonControl)))
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            
// 如果该控件不是“导出Excel”按钮则把button转换成文本
InBlock.gif
                            if (!c.Equals(e.CommandSource))
ExpandedSubBlockStart.gifContractedSubBlock.gif                            
dot.gif{
InBlock.gif                                tc.Controls.Clear();
InBlock.gif                                tc.Text 
= ((IButtonControl)c).Text;
ExpandedSubBlockEnd.gif                            }

ExpandedSubBlockEnd.gif                        }

ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

InBlock.gif
InBlock.gif                
// 将服务器控件的内容输出到所提供的 System.Web.UI.HtmlTextWriter 对象中
InBlock.gif
                this.RenderControl(htw);
InBlock.gif
InBlock.gif                System.Web.HttpContext.Current.Response.Write(sw.ToString());
InBlock.gif                System.Web.HttpContext.Current.Response.End();
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
base.OnRowCommand(e);
ExpandedBlockEnd.gif        }

None.gif


控件使用
添加这个控件到工具箱里,然后拖拽到webform上,在GridView内加一个按钮,把CommandName属性设置为“ExportToExcel”,CommandArgument属性的值用“;”做分隔符分为两部分,左边的部分为导出Excel的文件名称,右边的部分为需要隐藏的列的索引(列索引用“,”分开)
ObjData.cs
None.gif using  System;
None.gif
using  System.Data;
None.gif
using  System.Configuration;
None.gif
using  System.Web;
None.gif
using  System.Web.Security;
None.gif
using  System.Web.UI;
None.gif
using  System.Web.UI.WebControls;
None.gif
using  System.Web.UI.WebControls.WebParts;
None.gif
using  System.Web.UI.HtmlControls;
None.gif
None.gif
using  System.ComponentModel;
None.gif
ExpandedBlockStart.gifContractedBlock.gif
/**/ /// <summary>
InBlock.gif
/// OjbData 的摘要说明
ExpandedBlockEnd.gif
/// </summary>

None.gif public   class  OjbData
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
public OjbData()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
//
InBlock.gif        
// TODO: 在此处添加构造函数逻辑
InBlock.gif        
//
ExpandedSubBlockEnd.gif
    }

InBlock.gif
InBlock.gif    [DataObjectMethod(DataObjectMethodType.Select, 
true)]
InBlock.gif    
public DataTable Select()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        DataTable dt 
= new DataTable();
InBlock.gif        dt.Columns.Add(
"no"typeof(string));
InBlock.gif        dt.Columns.Add(
"name"typeof(string));
InBlock.gif
InBlock.gif        
for (int i = 0; i < 30; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            DataRow dr 
= dt.NewRow();
InBlock.gif            dr[
0= "no" + i.ToString().PadLeft(2'0');
InBlock.gif            dr[
1= "name" + i.ToString().PadLeft(2'0');
InBlock.gif
InBlock.gif            dt.Rows.Add(dr);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
return dt;
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

Default.aspx
ExpandedBlockStart.gif ContractedBlock.gif <% dot.gif @ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"  %>
None.gif
None.gif
<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
None.gif
< html  xmlns ="http://www.w3.org/1999/xhtml" >
None.gif
< head  runat ="server" >
None.gif    
< title > SmartGridView测试 </ title >
None.gif
</ head >
None.gif
< body >
None.gif    
< form  id ="form1"  runat ="server" >
None.gif        
< div >
None.gif            
< yyc:SmartGridView  ID ="SmartGridView1"  runat ="server"  AutoGenerateColumns ="False"
None.gif                DataSourceID
="ObjectDataSource1" >
None.gif                
< Columns >
None.gif                    
< asp:TemplateField  ItemStyle-Width ="50px" >
None.gif                        
< headertemplate >
None.gif                            
< asp:Button  id ="btnExportToExcel"  runat ="server"  Text ="Excel"  CommandName ="ExportToExcel"  CommandArgument ="ExcelFileName;5,6"   />
None.gif                        
</ headertemplate >
None.gif                        
< itemtemplate >
ExpandedBlockStart.gifContractedBlock.gif                            
<% dot.gif # Container.DataItemIndex + 1  %>
None.gif                        
</ itemtemplate >
None.gif                    
</ asp:TemplateField >
None.gif                    
< asp:BoundField  DataField ="no"  HeaderText ="序号"  SortExpression ="no"  ItemStyle-Width ="100px"   />
None.gif                    
< asp:BoundField  DataField ="name"  HeaderText ="名称"  SortExpression ="name"  ItemStyle-Width ="100px"   />
None.gif                    
< asp:BoundField  DataField ="no"  HeaderText ="序号"  SortExpression ="no"  ItemStyle-Width ="100px"   />
None.gif                    
< asp:BoundField  DataField ="name"  HeaderText ="名称"  SortExpression ="name"  ItemStyle-Width ="100px"   />
None.gif                    
< asp:BoundField  DataField ="no"  HeaderText ="序号"  SortExpression ="no"  ItemStyle-Width ="100px"   />
None.gif                    
< asp:BoundField  DataField ="name"  HeaderText ="名称"  SortExpression ="name"  ItemStyle-Width ="100px"   />
None.gif                
</ Columns >
None.gif            
</ yyc:SmartGridView >
None.gif            
< asp:ObjectDataSource  ID ="ObjectDataSource1"  runat ="server"  SelectMethod ="Select"
None.gif                TypeName
="OjbData" ></ asp:ObjectDataSource >
None.gif        
</ div >
None.gif    
</ form >
None.gif
</ body >
None.gif
</ html >
None.gif

注意:为了防止出错要在.cs代码中加上下面这句
None.gif public   override   void  VerifyRenderingInServerForm(Control control)
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif {
InBlock.gif
ExpandedBlockEnd.gif    }

另外,如果你的GridView中含有命令按钮的话要在.aspx页面的头部中加上下面这个属性
None.gif EnableEventValidation="false"


OK
[源码下载]

转载于:https://www.cnblogs.com/winner/archive/2007/01/31/635730.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值