导出Excel技术总结(2)

来源:互联网 发布:js如何获取鼠标的位置 编辑:程序博客网 时间:2024/05/20 11:33

3、从控件或页面获取


获取控件和页面的内容,如DataGird、GridView等,然后以Excel的ContentType输出到页面,适用于asp.net。利用Response.ContentType 属性,

设置为application/vnd.ms-excel,将文本数据以microsoft excel的格式输出(Response)到客户端。使用这种方法,可以将大部分控件的数据都导入到Excel文件中。

如Literal、GridView、Repeater、Label,只要这些控件中的数据是格式良好的表格,导出的Excel格式也是以表格数据形式展现。

代码示例:

        /// <summary>从指定控件导出指定类型的文件</summary>        /// <param name="ctl">DataGrid的ID</param>        /// <param name="FileType">导出文件类型//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword ;//application/ms-excel</param>        /// <param name="FileName">导出的文件名</param>        /// <returns>文件</returns>        public static void ExportDataGrid(System.Web.UI.Control ctl,string FileType, string FileName)         {                HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+FileName);                HttpContext.Current.Response.Charset ="gb2312";                HttpContext.Current.Response.ContentEncoding=System.Text.Encoding.UTF8;               //image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword ;//application/ms-excel               HttpContext.Current.Response.ContentType =FileType;               ctl.Page.EnableViewState =false;                System.IO.StringWriter tw = new System.IO.StringWriter() ;                   System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);                  ctl.RenderControl(hw);                HttpContext.Current.Response.Write(tw.ToString());                HttpContext.Current.Response.End();         } 

常见问题处理:只能在执行 Render() 的过程中调用 RegisterForEventValidation

4、PIA或Com组件
通过引用Excel PIA或者Excel Com组件,按照面向对象的编程模式构造Excel。推荐使用Excel PIA。

使用Office PIA之前需要安装,如果没有安装Office,需要先下载安装:
Office 2007 Primary Interop Assemblies
Office 2003 Primary Interop Assemblies

PIA会安装到Visual Studio的安装目录,引用的时候需要注意,不是引用Com对象。
pia reference 使用Office PIA生成Excel并释放资源

 ASP.NET使用Excel Application组件生成Excel

asp.net使用Microsoft.Office.Interop.Excel组件生成Excel,附详细实例。

 下载示例代码

下载解决asp.net中访问Excel权限问题的文档
原创粉丝点击