首页 > 代码库 > 将Asp.Net页面输出到EXCEL里去

将Asp.Net页面输出到EXCEL里去

 其实,利用ASP.NET输出指定内容的WORD、EXCEL、TXT、HTM等类型的文档很容易的。主要分为三步来完成。 

 一、定义文档类型、字符编码  

 

     Response.Clear();

   Response.Buffer= true;

   Response.Charset="utf-8";  

   //下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开

   //filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc    .xls    .txt   .htm  

   Response.AppendHeader("Content-Disposition","attachment;filename=FileFlow.xls");

   Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");  

   //Response.ContentType指定文件类型 可以为application/ms-excel    application/ms-word    application/ms-txt    application/ms-html    或其他浏览器可直接支持文档 

   Response.ContentType = "application/ms-excel";

   this.EnableViewState = false;  

 

  二、定义一个输入流  

 

     System.IO.StringWriter oStringWriter = new System.IO.StringWriter();

   System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

 

  三、将目标数据绑定到输入流输出  

 

     this.RenderControl(oHtmlTextWriter);   

   //this 表示输出本页,你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件  

   Response.Write(oStringWriter.ToString());

   Response.End();  

 

  总结:本例程在Microsoft Visual Studio .NET 2003平台下测试通过,适用于C#和VB,当采用VB的时候将 this 关键字改成 me 。 

<iframe id="google_ads_frame2" vspace="0" height="250" marginHeight="0" src="http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-3447371224873639&output=html&h=250&slotname=8660799060&adk=1970350646&w=300&lmt=1399271693&flash=0&url=http%3A%2F%2Fwww.cnblogs.com%2Franran%2Fp%2F3707288.html&dt=1399271697159&shv=r20140429&cbv=r20140417&saldr=sb&prev_slotnames=4356862740&correlator=1399271697059&frm=20&ga_vid=429972749.1397695120&ga_sid=1399267813&ga_hid=1579804484&ga_fc=1&u_tz=480&u_his=159&u_java=1&u_h=768&u_w=1364&u_ah=740&u_aw=1364&u_cd=16&u_nplug=0&u_nmime=0&dff=verdana&dfs=13&adx=0&ady=1812&biw=314&bih=74&eid=317150304&oid=3&rx=0&eae=0&docm=9&vis=0&fu=0&ifi=2&xpc=5unNado3zo&p=http%3A//www.cnblogs.com&dtd=41" frameBorder="0" width="300" allowTransparency="true" name="google_ads_frame2" marginWidth="0" scrolling="no" hspace="0"></iframe><iframe id="google_ads_frame3" vspace="0" height="250" marginHeight="0" src="http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-3447371224873639&output=html&h=250&slotname=8660799060&adk=1970350646&w=300&lmt=1399271693&flash=0&url=http%3A%2F%2Fwww.cnblogs.com%2Franran%2Fp%2F3707288.html&dt=1399271697208&shv=r20140429&cbv=r20140417&saldr=sb&prev_slotnames=4356862740%2C8660799060&correlator=1399271697059&frm=20&ga_vid=429972749.1397695120&ga_sid=1399267813&ga_hid=1579804484&ga_fc=1&u_tz=480&u_his=159&u_java=1&u_h=768&u_w=1364&u_ah=740&u_aw=1364&u_cd=16&u_nplug=0&u_nmime=0&dff=verdana&dfs=13&adx=305&ady=2062&biw=314&bih=74&eid=317150304&oid=3&rx=0&eae=0&docm=9&vis=0&fu=0&ifi=3&xpc=wMelVYzoOX&p=http%3A//www.cnblogs.com&dtd=40" frameBorder="0" width="300" allowTransparency="true" name="google_ads_frame3" marginWidth="0" scrolling="no" hspace="0"></iframe>