扩展GridView控件(8) - 导出数据源的数据为Excel、Word或Text

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


扩展GridView控件(8) - 导出数据源的数据为Excel、Word或Text


作者: webabcd

/*正式版的实现 开始*/
 
介绍
扩展GridView控件:
导出数据源的数据为Excel、Word或Text(应保证数据源的类型为DataTable或DataSet)

使用方法:
为SmartGridView添加的方法
Export(string fileName)
Export(string fileName, ExportFormat exportFormat)
Export(string fileName, ExportFormat exportFormat, Encoding encoding)
Export(string fileName, int[] columnIndexList, ExportFormat exportFormat, Encoding encoding)
Export(string fileName, int[] columnIndexList, string[] headers, ExportFormat exportFormat, Encoding encoding)
Export(string fileName, string[] columnNameList, ExportFormat exportFormat, Encoding encoding)
Export(string fileName, string[] columnNameList, string[] headers, ExportFormat exportFormat, Encoding encoding)



关键代码
using System; 
using System.Collections.Generic; 
using System.Text; 
 
using System.Data; 
using System.Web.UI.WebControls; 
 
namespace YYControls 

         /// <summary> 
         /// SmartGridView类的属性部分 
         /// </summary> 
         public partial  class SmartGridView 
        { 
                 /// <summary> 
                 /// 导出SmartGridView的数据源的数据 
                 /// </summary> 
                 /// <param name="fileName">文件名</param> 
                 /// <param name="exportFormat">导出文件的格式</param> 
                 /// <param name="encoding">编码</param> 
                 public  void Export( string fileName, ExportFormat exportFormat, Encoding encoding) 
                { 
                        DataTable dt = GetDataTable(); 
                        Helper.Common.Export(dt, exportFormat, fileName, encoding); 
                } 
 
                 /// <summary> 
                 /// 导出SmartGridView的数据源的数据 
                 /// </summary> 
                 /// <param name="fileName">文件名</param> 
                 /// <param name="exportFormat">导出文件的格式</param> 
                 public  void Export( string fileName, ExportFormat exportFormat) 
                { 
                        Export(fileName, exportFormat, Encoding.GetEncoding( "GB2312")); 
                } 
 
                 /// <summary> 
                 /// 导出SmartGridView的数据源的数据为Excel 
                 /// </summary> 
                 /// <param name="fileName">文件名</param> 
                 public  void Export( string fileName) 
                { 
                        Export(fileName, ExportFormat.CSV); 
                } 
 
                 /// <summary> 
                 /// 导出SmartGridView的数据源的数据 
                 /// </summary> 
                 /// <param name="fileName">输出文件名</param> 
                 /// <param name="columnIndexList">导出的列索引数组</param> 
                 /// <param name="exportFormat">导出文件的格式</param> 
                 /// <param name="encoding">编码</param> 
                 public  void Export( string fileName, int[] columnIndexList, ExportFormat exportFormat, Encoding encoding) 
                { 
                        DataTable dt = GetDataTable(); 
 
                        Helper.Common.Export(dt, columnIndexList, exportFormat, fileName, encoding); 
                } 
 
                 /// <summary> 
                 /// 导出SmartGridView的数据源的数据 
                 /// </summary> 
                 /// <param name="fileName">输出文件名</param> 
                 /// <param name="columnNameList">导出的列的列名数组</param> 
                 /// <param name="exportFormat">导出文件的格式</param> 
                 /// <param name="encoding">编码</param> 
                 public  void Export( string fileName,  string[] columnNameList, ExportFormat exportFormat, Encoding encoding) 
                { 
                        DataTable dt = GetDataTable(); 
 
                        Helper.Common.Export(dt, columnNameList, exportFormat, fileName, encoding); 
                } 
 
                 /// <summary> 
                 /// 导出SmartGridView的数据源的数据 
                 /// </summary> 
                 /// <param name="fileName">输出文件名</param> 
                 /// <param name="columnIndexList">导出的列索引数组</param> 
                 /// <param name="headers">导出的列标题数组</param> 
                 /// <param name="exportFormat">导出文件的格式</param> 
                 /// <param name="encoding">编码</param> 
                 public  void Export( string fileName,  int[] columnIndexList,  string[] headers, ExportFormat exportFormat, Encoding encoding) 
                { 
                        DataTable dt = GetDataTable(); 
 
                        Helper.Common.Export(dt, columnIndexList, headers, exportFormat, fileName, encoding); 
                } 
 
                 /// <summary> 
                 /// 导出SmartGridView的数据源的数据 
                 /// </summary> 
                 /// <param name="fileName">输出文件名</param> 
                 /// <param name="columnNameList">导出的列的列名数组</param> 
                 /// <param name="headers">导出的列标题数组</param> 
                 /// <param name="exportFormat">导出文件的格式</param> 
                 /// <param name="encoding">编码</param> 
                 public  void Export( string fileName,  string[] columnNameList,  string[] headers, ExportFormat exportFormat, Encoding encoding) 
                { 
                        DataTable dt = GetDataTable(); 
 
                        Helper.Common.Export(dt, columnNameList, headers, exportFormat, fileName, encoding); 
                } 
 
                 /// <summary> 
                 /// 获取数据源(DataTable) 
                 /// </summary> 
                 private DataTable GetDataTable() 
                { 
                        DataTable dt =  null
 
                         if ( this._dataSourceObject  is DataTable) 
                                dt = (DataTable) this._dataSourceObject; 
                         else  if ( this._dataSourceObject  is DataSet) 
                                dt = ((DataSet) this._dataSourceObject).Tables[0]; 
                         else 
                                 throw  new InvalidCastException( "若要导出SmartGridView,应保证其数据源为DataTable或DataSet类型"); 
 
                         if (dt ==  null
                                 throw  new ArgumentNullException( "数据源""数据源不能为NULL"); 
 
                         return dt; 
                } 
        } 
}
 
/*正式版的实现 结束*/
 
/*测试版的实现 开始*/
 
介绍
把GridView导出为一个Excel文件算是一个经常要用到的功能,也比较简单,我们来扩展一个GridView以实现这样的功能。


控件开发
1、新建一个继承自GridView的类。
/// <summary> 
/// 继承自GridView 
/// </summary> 
[ToolboxData( @"<{0}:SmartGridView runat='server'></{0}:SmartGridView>")] 
public  class SmartGridView : GridView 

}
 
2、重写OnRowCommand,以实现把GridView导出为Excel的功能
  /// <summary> 
                 /// OnRowCommand 
                 /// </summary> 
                 /// <param name="e"></param> 
                 protected  override  void OnRowCommand(GridViewCommandEventArgs e) 
                { 
                         if (e.CommandName.ToLower() ==  "exporttoexcel"
                        { 
                                System.Web.HttpContext.Current.Response.ClearContent(); 
                                 // e.CommandArgument用“;”隔开两部分,左边的部分为导出Excel的文件名称 
                                System.Web.HttpContext.Current.Response.AddHeader( "content-disposition""attachment; filename=" + e.CommandArgument.ToString().Split(';')[0] +  ".xls"); 
                                System.Web.HttpContext.Current.Response.ContentType =  "application/excel"
 
                                System.IO.StringWriter sw =  new System.IO.StringWriter(); 
                                HtmlTextWriter htw =  new HtmlTextWriter(sw); 
 
                                 // e.CommandArgument用“;”隔开两部分,右边的部分为需要隐藏的列的索引(列索引用“,”分开) 
                                 if (e.CommandArgument.ToString().Split(';').Length > 1) 
                                { 
                                         foreach ( string s  in e.CommandArgument.ToString().Split(';')[1].Split(',')) 
                                        { 
                                                 int i; 
 
                                                 if (!Int32.TryParse(s,  out i)) 
                                                { 
                                                         throw  new ArgumentException( "需要隐藏的列的索引不是整数");    
                                                } 
 
                                                 if (i >  this.Columns.Count) 
                                                { 
                                                         throw  new ArgumentOutOfRangeException( "需要隐藏的列的索引超出范围"); 
                                                } 
 
                                                 this.Columns[i].Visible =  false
                                        } 
                                } 
 
                                 // 隐藏“导出Excel”按钮 
                                ((Control)e.CommandSource).Visible =  false
 
                                 // 如果HeaderRow里的控件是button的话,则把它替换成文本 
                                 foreach (TableCell tc  in  this.HeaderRow.Cells) 
                                { 
                                         // TableCell里的每个Control 
                                         foreach (Control c  in tc.Controls) 
                                        { 
                                                 // 如果控件继承自接口IButtonControl 
                                                 if (c.GetType().GetInterface( "IButtonControl") !=  null && c.GetType().GetInterface( "IButtonControl").Equals( typeof(IButtonControl))) 
                                                { 
                                                         // 如果该控件不是“导出Excel”按钮则把button转换成文本 
                                                         if (!c.Equals(e.CommandSource)) 
                                                        { 
                                                                tc.Controls.Clear(); 
                                                                tc.Text = ((IButtonControl)c).Text; 
                                                        } 
                                                } 
                                        } 
                                } 
 
                                 // 将服务器控件的内容输出到所提供的 System.Web.UI.HtmlTextWriter 对象中 
                                 this.RenderControl(htw); 
 
                                System.Web.HttpContext.Current.Response.Write(sw.ToString()); 
                                System.Web.HttpContext.Current.Response.End(); 
                        } 
 
                         base.OnRowCommand(e); 
                }
 
控件使用
添加这个控件到工具箱里,然后拖拽到webform上,在GridView内加一个按钮,把CommandName属性设置为“ExportToExcel”,CommandArgument属性的值用“;”做分隔符分为两部分,左边的部分为导出Excel的文件名称,右边的部分为需要隐藏的列的索引(列索引用“,”分开)
ObjData.cs
using System; 
using System.Data; 
using System.Configuration; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 
 
using System.ComponentModel; 
 
/// <summary> 
/// OjbData 的摘要说明 
/// </summary> 
public  class OjbData 

         public OjbData() 
        { 
                 // 
                 // TODO: 在此处添加构造函数逻辑 
                 // 
        } 
 
        [DataObjectMethod(DataObjectMethodType.Select,  true)] 
         public DataTable Select() 
        { 
                DataTable dt =  new DataTable(); 
                dt.Columns.Add( "no"typeof( string)); 
                dt.Columns.Add( "name"typeof( string)); 
 
                 for ( int i = 0; i < 30; i++) 
                { 
                        DataRow dr = dt.NewRow(); 
                        dr[0] =  "no" + i.ToString().PadLeft(2, '0'); 
                        dr[1] =  "name" + i.ToString().PadLeft(2, '0'); 
 
                        dt.Rows.Add(dr); 
                } 
 
                 return dt; 
        } 
}
 
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
        <title>SmartGridView测试</title> 
</head> 
<body> 
        <form id="form1" runat="server"> 
                <div> 
                        <yyc:SmartGridView ID="SmartGridView1" runat="server" AutoGenerateColumns="False" 
                                DataSourceID="ObjectDataSource1"> 
                                <Columns> 
                                        <asp:TemplateField ItemStyle-Width="50px"> 
                                                <headertemplate> 
                                                        <asp:Button id="btnExportToExcel" runat="server" Text="Excel" CommandName="ExportToExcel" CommandArgument="ExcelFileName;5,6" /> 
                                                </headertemplate> 
                                                <itemtemplate> 
                                                        <%# Container.DataItemIndex + 1 %> 
                                                </itemtemplate> 
                                        </asp:TemplateField> 
                                        <asp:BoundField DataField="no" HeaderText="序号" SortExpression="no" ItemStyle-Width="100px" /> 
                                        <asp:BoundField DataField="name" HeaderText="名称" SortExpression="name" ItemStyle-Width="100px" /> 
                                        <asp:BoundField DataField="no" HeaderText="序号" SortExpression="no" ItemStyle-Width="100px" /> 
                                        <asp:BoundField DataField="name" HeaderText="名称" SortExpression="name" ItemStyle-Width="100px" /> 
                                        <asp:BoundField DataField="no" HeaderText="序号" SortExpression="no" ItemStyle-Width="100px" /> 
                                        <asp:BoundField DataField="name" HeaderText="名称" SortExpression="name" ItemStyle-Width="100px" /> 
                                </Columns> 
                        </yyc:SmartGridView> 
                        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="Select" 
                                TypeName="OjbData"></asp:ObjectDataSource> 
                </div> 
        </form> 
</body> 
</html>
 
注:为了防止出错要在.cs代码中加上下面这句
public  override  void VerifyRenderingInServerForm(Control control) 
        { 
 
        }
 
另外,如果你的GridView中含有命令按钮的话要在.aspx页面的头部中加上下面这个属性
EnableEventValidation= "false"
 
/*测试版的实现 结束*/
 





     本文转自webabcd 51CTO博客,原文链接:http://blog.51cto.com/webabcd/345538,如需转载请自行联系原作者

相关文章
|
18天前
|
数据采集 数据可视化 数据挖掘
利用Python自动化处理Excel数据:从基础到进阶####
本文旨在为读者提供一个全面的指南,通过Python编程语言实现Excel数据的自动化处理。无论你是初学者还是有经验的开发者,本文都将帮助你掌握Pandas和openpyxl这两个强大的库,从而提升数据处理的效率和准确性。我们将从环境设置开始,逐步深入到数据读取、清洗、分析和可视化等各个环节,最终实现一个实际的自动化项目案例。 ####
|
1月前
|
Java API Apache
Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
【10月更文挑战第29天】Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
131 5
|
24天前
|
前端开发
实现Excel文件和其他文件导出为压缩包,并导入
实现Excel文件和其他文件导出为压缩包,并导入
27 1
|
27天前
|
数据格式 UED
记录一次NPOI库导出Excel遇到的小问题解决方案
【11月更文挑战第16天】本文记录了使用 NPOI 库导出 Excel 过程中遇到的三个主要问题及其解决方案:单元格数据格式错误、日期格式不正确以及合并单元格边框缺失。通过自定义单元格样式、设置数据格式和手动添加边框,有效解决了这些问题,提升了导出文件的质量和用户体验。
158 3
|
2月前
|
数据处理 Python
Python实用记录(十):获取excel数据并通过列表的形式保存为txt文档、xlsx文档、csv文档
这篇文章介绍了如何使用Python读取Excel文件中的数据,处理后将其保存为txt、xlsx和csv格式的文件。
75 3
Python实用记录(十):获取excel数据并通过列表的形式保存为txt文档、xlsx文档、csv文档
|
1月前
|
Java API Apache
|
1月前
|
存储 Java API
Java实现导出多个excel表打包到zip文件中,供客户端另存为窗口下载
Java实现导出多个excel表打包到zip文件中,供客户端另存为窗口下载
47 4
|
2月前
|
JavaScript 前端开发 数据处理
Vue导出el-table表格为Excel文件的两种方式
Vue导出el-table表格为Excel文件的两种方式
91 6
|
2月前
|
easyexcel Java UED
SpringBoot中大量数据导出方案:使用EasyExcel并行导出多个excel文件并压缩zip后下载
在SpringBoot环境中,为了优化大量数据的Excel导出体验,可采用异步方式处理。具体做法是将数据拆分后利用`CompletableFuture`与`ThreadPoolTaskExecutor`并行导出,并使用EasyExcel生成多个Excel文件,最终将其压缩成ZIP文件供下载。此方案提升了导出效率,改善了用户体验。代码示例展示了如何实现这一过程,包括多线程处理、模板导出及资源清理等关键步骤。
|
2月前
|
前端开发 JavaScript Java
导出excel的两个方式:前端vue+XLSX 导出excel,vue+后端POI 导出excel,并进行分析、比较
这篇文章介绍了使用前端Vue框架结合XLSX库和后端结合Apache POI库导出Excel文件的两种方法,并对比分析了它们的优缺点。
738 0